就這個(gè)程序進(jìn)行分析阀坏,在第一次添加時(shí),調(diào)用了hashcode()方法赔退,將hashcode存入對(duì)象中,第二次也一樣,然后對(duì)hashcode進(jìn)行比較硕旗。hashcode也只用于HashSet/HashMap/Hashtable類存儲(chǔ)數(shù)據(jù)窗骑,所以會(huì)用于比較,需要重寫
總結(jié)漆枚,自定義類要重寫equals方法來(lái)進(jìn)行等值比較创译,自定義類要重寫compareTo方法來(lái)進(jìn)行不同對(duì)象大小的比較,重寫hashcode方法為了將數(shù)據(jù)存入HashSet/HashMap/Hashtable類時(shí)進(jìn)行比較
import java.util.*;
public class HelloWorld {
public static void main(String[] args) {
Name n1 = new Name("01");
Name n2 = new Name("01");
Collection c = new HashSet();
c.add(n1);
System.out.println("------------");
c.add(n2);
System.out.println("------------");
System.out.println(n1.equals(n2));
System.out.println("------------");
System.out.println(n1.hashCode());
System.out.println(n2.hashCode());
System.out.println(c);
}
}
class Name {
private String id;
public Name(String id) {
this.id = id;
}
public String toString(){
return this.id;
}
public boolean equals(Object obj) {
if (obj instanceof Name) {
Name name = (Name) obj;
System.out.println("equal"+ name.id);
return (id.equals(name.id));
}
return super.equals(obj);
}
public int hashCode() {
Name name = (Name) this;
System.out.println("Hash" + name.id);
return id.hashCode();
}
}