基于hash的map也是这种机制。
HashSet
import java.util.HashSet; import java.util.Set; import java.util.TreeSet; public class Sets { public static void main(String[] args) { // TODO Auto-generated method stub Person p1 = new Person("320321"); p1.setAge(22); p1.setName("p1"); Person p2 = new Person("320321"); p2.setAge(23); p2.setName("p2"); Person p3 = new Person("320322"); p3.setAge(22); p3.setName("p3"); Person p4=new Person("320321"); p4.setAge(22); p4.setName("p4"); HashSet<Person> hashSet = new HashSet(); /* * Add elements */ // p1 equals p2, p1.hashCode != p2.hashCode hashSet.add(p1); hashSet.add(p2); // p1, p2 System.out.println(hashSet); // p3 not equals p1, p2, but p3.hashCode == p1.hashCode hashSet.add(p3); // p1, p3, p2 System.out.println(hashSet); // p4 equals p1, p2, and p4.hashCode == p1.hashCode hashSet.add(p4); // p1, p3, p2, without p4 System.out.println(hashSet); /* * Remove elements. Now, the SET contains p1, p3, p2 */ hashSet.remove(p4); // p1 will be removed, since p1 equals p4 and p1.hashCode == p4.hashCode System.out.println(hashSet); // Although the SET contains p2 who equals p4, but can't find "p4" // Also, p3.hashCode == p4.hashCode but not find "p4" in the same bucket System.out.println(hashSet.contains(p4)); } }
Person
public class Person implements Comparable<Person> { private String name, id, gender; private int age; private String[] property; public Person() { } public Person(String id) { this.id = id; } public String getId() { return id; } public void setName(String name) { this.name = name; } public void setGender(String gender) { this.gender = gender; } public void setAge(int age) { this.age = age; } public String getName() { return name; } public String getGender() { return gender; } public int getAge() { return age; } public String[] getProperty() { return property; } public void setProperty(String[] property) { this.property = property; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof Person)) { return false; } Person p = (Person) o; if (id == null ? p.getId() == null : id.equals(p.getId())) { return true; } return false; } @Override public int hashCode() { return age; } @Override public String toString() { return this.id + " age: " + this.age + " name: " + this.name; } @Override public Person clone() { Person p = null; try { p = (Person) super.clone(); p.setProperty(property.clone()); } catch (CloneNotSupportedException e) { // TODO Auto-generated catch block e.printStackTrace(); } return p; } @Override public int compareTo(Person p) { return this.age - p.getAge(); } }