HashSet的面试题
作者:互联网
HashSet的面试题
public class HashSetTest {
@Test
public void test(){
HashSet set = new HashSet();
Person p1 = new Person(1001, "AA");
Person p2 = new Person(1002, "BB");
set.add(p1);
set.add(p2);
p1.name = "CC";
//remove()会判断哈希值,因为此时已经修改了p1.name,大概率会和之前的p1不同,所有删除不了
boolean remove = set.remove(p1);
System.out.println(remove);//false
System.out.println(set);//[Person{id=1002, name='BB'}, Person{id=1001, name='CC'}]
//第一次的1001CC的哈希值实际上是1001AA的哈希值,所以哈希值不一样
set.add(new Person(1001,"CC"));
System.out.println(set);//[Person{id=1002, name='BB'}, Person{id=1001, name='CC'}, Person{id=1001, name='CC'}]
//虽然此次的1001AA和第一次的1001AA的哈希值一样,但是equals()比较的时候,由于第一次1001AA已经改为1001CC,所有能添加进去
set.add(new Person(101,"AA"));
System.out.println(set);//[Person{id=1002, name='BB'}, Person{id=1001, name='CC'}, Person{id=1001, name='CC'}, Person{id=101, name='AA'}]
}
}
标签:面试题,set,name,HashSet,CC,Person,id,1001 来源: https://www.cnblogs.com/czhai/p/15946772.html