equals 與 compareTo 在 Java 中有什麼區別?
compareTo() 方法按字典序比較兩個字串。比較基於字串中每個字元的 Unicode 值。該字串物件表示的字元序列將按字典序與 arg 字元序列進行比較。
- 如果該字串物件在字典序中的位置在引數字串之前,結果將為負整型。
- 如果該字串物件在字典序中的位置在引數字串之後,結果將為正整型。
- 如果字串相等,結果為零,當且僅當 equals(Object) 方法返回 true 時,compareTo 返回 0。
示例
public class StringDemo {
public static void main(String[] args) {
String str1 = "tutorials", str2 = "point";
// comparing str1 and str2
int retval = str1.compareTo(str2);
// prints the return value of the comparison
if (retval < 0) {
System.out.println("str1 is greater than str2");
} else if (retval == 0) {
System.out.println("str1 is equal to str2");
} else {
System.out.println("str1 is less than str2");
}
}
}輸出
str1 is less than str2
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP