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

更新於: 2020 年 6 月 18 日

2 千 + 次瀏覽

開啟您的 職業生涯

完成課程以獲得認證

開始
廣告
© . All rights reserved.