2013-02-17 127 views
0

我被檢查的字符串比較方法用於字符串compsrsion探索串類的decomplier,來到知道,基本上有四種方法關於字符串比較

equals() 
equalsIgnoreCase() 
compareTo() 
compareToIgnore() 

現在我想知道的區別我們使用他們的equals()和的compareTo()兩種方法,基本上請指教爲什麼string類一直保持這兩種方法..

String tv = "Bravia"; 
     String television = "Bravia"; 

     // String compare example using equals 
     if (tv.equals(television)) { 
      System.out.println("Both tv and television contains same letters and equal by equals method of String"); 
     } 

     // String compare example in java using compareTo 
     if (tv.compareTo(television) == 0) { 
      System.out.println("Both tv and television are equal using compareTo method of String"); 
     } 

輸出: -

Both tv and television contains same letters and equal by equals method of String 
Both tv and television are equal using compareTo method of String 
+0

你問返回true。我已經實現了它... – Ahmad 2013-02-17 06:56:41

回答

0

字符串實現Comparable接口然後綁定實現compareTo方法。

Camparable接口

當它們包含在任何分類收集它有利於目標的排序。所以當你將你的字符串放入任何已排序的集合(如TreeSet)時,如何告訴java如何對對象進行排序。這就是coompareTo()方法出現的地方。它被集合用來排序你的對象。

String tv = "Bravia"; 
    String television = "Bravia"; 

    // String compare example using equals 
    if (tv.equals(television)) { 
     System.out.println("Both tv and television contains same letters and equal by equals method of String"); 
    } 

    // String compare example in java using compareTo 
    if (tv.compareTo(television) == 0) { 
     System.out.println("Both tv and television are equal using compareTo method of String"); 
    } 

    if (tv.compareTo(television) < 0){ 

    System.out.println("tv comes before using compareTo method of String"); 
    } 

if (tv.compareTo(television) > 0){ 

    System.out.println("tv comes after using compareTo method of String"); 
    } 
2

equals()返回boolean; true/false。字符串A是否等於B?

compareTo()返回一個整數,不僅表示字符串是否相等,而且哪一個比另一個「低」,將「lower」定義爲自然字母順序。

對於兩個字符串aba.equals(b)只有在a.compareTo(b)0的情況下才成立。

例如:(!不一定-1

String a = "String1"; 
String b = "String2"; 

a.compareTo(b)將返回負整數,因爲,按字母順序,字符串 「String1中」 比 「String2的」 低級;如果要按升序對兩個字符串進行排序,則會首先出現「String1」。另外,a.equals(b)將返回false,因爲字符串不相等。

但是:

String a = "Example"; 
String b = "Example"; 

在這種情況下,a.compareTo(b)將返回0(因爲字符串相等),並a.equals(b)將返回true(再次,因爲字符串相等)。

關於 「IGNORECASE」 變種:

String a = "String1"; 
String b = "string1"; 

在這種情況下,a.compareToIgnoreCase(b)將返回0;這是因爲,當案件被忽略時,兩個字符串是相同的。同樣,a.equalsIgnoreCase(b)將返回0,出於同樣的原因。

+0

非常感謝,對於compareTo()你能請一個例子解釋一下,這樣我就可以完全理解 – user2045633 2013-02-17 06:44:59

+0

是的,只是做了... – Isaac 2013-02-17 06:50:32

1

equalsequalsIgnoreCase返回boolean值,該值表示 「一個或者是等於另一個,或者不是」

compareTocompareToIgnoreCase()返回一個三態整數,0-11

  • 0如果他們平等地比較每個正常
  • 1如果 參數compareTo*()中大於對象序你
  • -1調用compareTo*()如果參數compareTo*()是比你調用compareTo*()對象 序較小。
0

兩種方法都是必需的。字符串從Object繼承,ObjectTo在實現Comparable接口時是必需的。

+0

你能否給我們展示一個compareTo的小例子。 – user2045633 2013-02-17 06:47:35

0

compareTo():返回一個負整數,零或正整數,根據此對象是比指定的對象小於,等於,或更大。從compareTo()

equals():本equals()方法比較相等的兩個對象,如果他們是平等的,否則返回虛假源here