Set不能存取重复的对象
如
Set<String> set = new hashSet<String>();
set.add("abc");
set.add("abc");
set.add("cd");
set.add("cd");
Iterator it = set.iterator();
while(it.hasNext()){
Sysotem.out,println(it.next());
}
如上结果所示,存入相同元素,结果只会存入一次,如上输出所示。
hashSet为Set的实现类,与set类似也不能存入相同元素,有情况如下
HashSet<String> set = new HashSet<String>();
set.add(new String("abc")); //四个add的皆为new的String对象,虽然对象初始化相同,但却不是重复对象
set.add(new String("abc"));
set.add(new String("bc"));
set.add(new String("bc"));
System.out.println(set);
如上结果中也是只有两个元素,但原因与第一个示例不同,new String(“abc”),add时集合调用对象的哈希值即new String(“abc”).hashCode()=96354,String类对象哈希值测算方法可参考源码hashCode()方法,集合在容器内寻找有没有哈希值为96354的对象,即能找到第一个存入的new String(“abc”),然后集合会让后来的对象new String(“abc”)调用equals(),与已有的对象相比,两个对象哈希值一样,equals方法返回true,则集合判定元素重复,因此集合就不会存后来的对象了。