代码:
Collections.sort(mylist, new Comparator<String>(){
public int compare(String a, String b){
return a.compareToIgnoreCase(b);
}
});
第一个参数是一个list<String>, 问一下我查看api发现Comparator接口有两个方法,一个compare,一个equals,为什么这里只实现了一个compare就当做参数传给sort了,equals不用实现吗? 谢谢 。

解决方案 »

  1.   

    没有重写的都是从Object继承的equals。
      

  2.   

    effective java 2-Item 12: Consider implementing ComparableIt is strongly recommended, but not strictly required, that (x.compareTo(y)
    == 0) == (x.equals(y)). Generally speaking, any class that implements the
    Comparable interface and violates this condition should clearly indicate this
    fact. The recommended language is “Note: This class has a natural ordering
    that is inconsistent with equals.”The final paragraph of the compareTo contract, which is a strong suggestion
    rather than a true provision, simply states that the equality test imposed by the
    compareTo method should generally return the same results as the equals
    method. If this provision is obeyed, the ordering imposed by the compareTo
    method is said to be consistent with equals. If it’s violated, the ordering is said to
    be inconsistent with equals. A class whose compareTo method imposes an order
    that is inconsistent with equals will still work, but sorted collections containing
    elements of the class may not obey the general contract of the appropriate collection
    interfaces (Collection, Set, or Map). This is because the general contracts
    for these interfaces are defined in terms of the equals method, but sorted collections
    use the equality test imposed by compareTo in place of equals. It is not a
    catastrophe if this happens, but it’s something to be aware of.
      

  3.   

    java中一切类(Object除外)的根都是Object,也就是Object以外的其他类都是Object的子类,Object带有equals方法,所以子类也会带有equals方法,所以Comparetor的equals方法可以不用实现,沿用Object自带的equals方法