HashSet set=new HashSet();set.add("a");set.add("b");set.add("c");set.add("d");System.out.println(set);//结果:[d,b,c,a]2.Set不允许重复 情景0
HashSet set=new HashSet();System.out.println(set.add("a"));//结果:trueset.add("b");set.add("c");set.add("d");System.out.println(set.add("a"));//结果:false两次添加"a" 情景1
HashSet set=new HashSet();System.out.println(set.add(new People("张三")));//trueSystem.out.println(set.add(new People("张三")));//true两次分别添加不同的对象。 情景2
HashSet set=new HashSet(); People p1=new People("张三");System.out.println(set.add(p1));//trueSystem.out.println(set.add(p1));//false两次都是添加p1 情景3
HashSet set=new HashSet(); String s1=new String("a");String s2=new String("a");System.out.println(set.add(s1));//trueSystem.out.println(set.add(s2));//false
两次分别添加s1,s2(显然,s1和s2是不同的对象)。
注意:此时第二次添加并不成功。 HashSet添加元素的过程 ①HashCode 当HashSet在添加元素时,会先调用hashCode()方法,判断即将加入的元素的hashCode是否与集合中的元素有相同的,如果没有,则允许添加该元素。如果有相同的,则继续调用equals()方法,如果equals()方法返回true,则表示对象已经加入过了,不允许再添加了。否则,如果equels方法返回false,则允许添加新元素。 ②equals 对于两个对象来说,如果使用equals返回true, 则这两个对象的hashcode一定相同。 对于两个对象来说,如果使用equals返回false,则这两个对象的hashcode不一定不相同(可以相同或者不同)。如果不同,可以提高性能。 对于Object类来说,不同的Object对象的hashcode值是不同的(hashCode值表示对象的地址) String类的hashCode()方法重写了Object类的hashCode()方法,只要两个String对象的内容相同则认为hashCode相同,所以情景3比较特殊。