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呀?

解决方案 »

  1.   

    你Debug一下,是不是出现如下的问题,我也遇到了和你相同的问题,一个师兄告诉我可能是某个lib库没加载上,还有同学告诉我说:可能是jdk版本的问题。你可以顺着这个思路去解决一下
    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]
      

  2.   

    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")));
    System.out.println(set.contains(t)); 

    } 第二个输出的结果为“true”
    原因是因为第一次输出时创建的对象虽然与之前创建的对象t相同
    但是却是不同的对象,用contains方法获得的结果为“false”