2013-02-17 125 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