HashSet不能添加重复的元素,当调用add(Object)方法时候,
首先会调用Object的hashCode方法判hashCode是否已经存在,如不存在则直接插入元素;
如果已存在则调用Object对象的equals方法判断是否返回true,如果为true则说明元素已经存在,如为false则插入元素。
package test2;
import java.util.HashSet;
public class Test {
class T{
int t;
T(int tt){
t = tt;
}
// public int hashCode(){
// Integer s = (Integer)t;
// return s.hashCode();
// }
//
// public boolean equals(Object o){
// return false;
// }
}
HashSet<T> hs;
public Test(){
hs = new HashSet<T>();
}
public static void main(String[] args){
Test t = new Test();
Test.T t1 = t.new T(5);
Test.T t2 = t.new T(5);//
t2 = t1;
boolean r1 = t.hs.add(t1);
boolean r2 = t.hs.add(t2);
System.out.println(""+r1+" "+r2);
}
}