equals 和 compareTo 在 Java 中的區別是什麼?


compareTo() 方法按字典順序比較兩個字串。比較基於字串中每個字元的 Unicode 值。此 String 物件表示的字元序列按字典順序與其引數字串表示的字元序列進行比較。

  • 結果為負整數,如果此 String 物件在字典順序上位於引數字串之前。
  •  結果為正整數,如果此 String 物件在字典順序上位於引數字串之後。
  •  結果為零,如果字串相等,則 compareTo 返回 0 且僅當 equals(Object) 方法返回 true 時才會返回 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 日

2K+ 瀏覽量

開啟你的 職業生涯

完成課程並獲得認證

開始學習
廣告
© . All rights reserved.