public class TT{
private final String first,last;
public TT(String first,String last){
this.first=first;
this.last=last;
}
public boolean equals(TT t){
return t.first.equals(first)&&t.last.equals(last);
}
public int hashCode(){
return 31*first.hashCode()+last.hashCode();
} public static void main(String[]args){
TT t=new TT("Han","han");
Set set=new HashSet();
set.add(t);
System.out.println(set.contains(new TT("Han","han")));
}
}
打印出false,为什么呢?我同时覆盖的hashcode和equals呀?
private final String first,last;
public TT(String first,String last){
this.first=first;
this.last=last;
}
public boolean equals(TT t){
return t.first.equals(first)&&t.last.equals(last);
}
public int hashCode(){
return 31*first.hashCode()+last.hashCode();
} public static void main(String[]args){
TT t=new TT("Han","han");
Set set=new HashSet();
set.add(t);
System.out.println(set.contains(new TT("Han","han")));
}
}
打印出false,为什么呢?我同时覆盖的hashcode和equals呀?
false
ERROR: JDWP Unable to get JNI 1.2 environment, jvm->GetEnv() return code = -2
JDWP exit error AGENT_ERROR_NO_JNI_ENV(183): [../../../src/share/back/util.c:820]
private final String first,last;
public TT(String first,String last){
this.first=first;
this.last=last;
}
public boolean equals(TT t){
return t.first.equals(first)&&t.last.equals(last);
}
public int hashCode(){
return 31*first.hashCode()+last.hashCode();
} public static void main(String[]args){
TT t=new TT("Han","han");
Set set=new HashSet();
set.add(t);
System.out.println(set.contains(new TT("Han","han")));
System.out.println(set.contains(t));
}
} 第二个输出的结果为“true”
原因是因为第一次输出时创建的对象虽然与之前创建的对象t相同
但是却是不同的对象,用contains方法获得的结果为“false”