何時應該覆蓋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