HashSet中是通过hashCode和equals()来判断的,可是我通过(t.count=3)将对象newTest(1)的hashCode设置成为了3,那为什么System.out.println(hs.contains(new Test(3)));输出为false
代码如下 :
import java.util.*;
class Test {
int count;
public Test(){
}
public Test(int count){
this.count = count;
}
@Override
public boolean equals(Object otherObject){
if(this == otherObject)
return true;
if(otherObject == null)
return false;
if(getClass() != otherObject.getClass())
return false;
Test other = (Test) otherObject;
return this.count == other.count;
}
@Override
public int hashCode(){
return this.count;
}
}
public class HashCodeTest{
public static void main(String[]args){
HashSet hs = new HashSet();
hs.add(new Test(1));
hs.add(new Test(2));
hs.add(new Test(3));
System.out.println(hs);
Iterator it = hs.iterator();
Test t = (Test) it.next();
t.count = 3;
System.out.println(hs);
System.out.println(hs.remove(new Test(3)));
System.out.println(hs);
System.out.println(hs.contains(new Test(3)));
System.out.println(hs.contains(new Test(1)));
}
} |
|