Java中的HashSet让我很困惑。当使用contains()方法时,它会查找hashcode()和equals()的结果吗?但是在某些情况下,它的行为并不正常。如果您将这种代码放入大型项目中,有时会出现问题。问题是为什么最后一条语句打印FALSE?contains()方法在底层做了什么?
class R
{
int count;
public R(int count)
{
this.count = count;
}
public String toString()
{
return "R(count attribution:" + count + ")";
}
public boolean equals(Object obj)
{
if (obj instanceof R)
{
R r = (R)obj;
if (r.count == this.count)
{
return true;
}
}
return false;
}
public int hashCode()
{
return this.count;
}
}
public class TestHashSet2
{
public static void main(String[] args)
{
HashSet hs = new HashSet();
hs.add(new R(5));
hs.add(new R(-3));
hs.add(new R(9));
hs.add(new R(-2));
System.out.println(hs);
//change first element
Iterator it = hs.iterator();
R first = (R)it.next();
first.count = -3;
System.out.println(hs);
//remove
hs.remove(new R(-3));
System.out.println(hs);
R r1 = new R(-3);
System.out.println(r1.hashCode());
Iterator i = hs.iterator();
R r2 = (R)i.next();
System.out.println(r2.hashCode()); //same hashcode -3
System.out.println(r1.equals(r2)); //equals true
System.out.println("hs contains object which count=-3 ?" + hs.contains(new R(-3))); //false
}
}