何时应该覆盖equals方法呢?web
覆盖equals须要注意哪些约定?ide
高质量的equals诀窍:svg
告诫:测试
public boolean equals(Object o) { ... } // 而不是 public boolean equals(MyObject o) { ... }
覆盖equals方法时不覆盖hashCode,就会违反hashCode的通用约定,从而致使该类没法结合全部基于散列的集合一块儿正常运做,这样的集合包括HashMap、HashSet和HashTable。flex
建议全部的子类都覆盖这个方法。code
public class Person implements Comparable { private String name; private int age; @Override public String toString() { return "Person{" + "name='" + name + '\'' + ", age=" + age + '}'; } public int compareTo(Object o) { if (o instanceof Person) { Person o1 = (Person) o; return o1.getName().compareTo(name) > 0 ? 1 : (o1.getName().compareTo(name) == 0 ? 0 : -1); } return 0; } public static void main(String[] args) { List<Person> peoples = new ArrayList<Person>( Arrays.asList( new Person("a", 1), new Person("b", 2), new Person("a", 1), new Person("d", 3), new Person("f", 5)) ); Collections.sort(peoples); peoples.forEach(people -> System.out.println(people)); } }
输出
xml