AbstractSet 抽象类代码研读
参考 https://www.cnblogs.com/magics/p/3633722.html
public int hashCode() {
int h = 0;
Iterator<E> i = iterator();
while (i.hasNext()) {
E obj = i.next();
if (obj != null)
h += obj.hashCode();
}
return h;
}
hashCode 集合遍历对象拿到hashCode,在相加
public boolean equals(Object o) {
if (o == this)
return true;
if (!(o instanceof Set))
return false;
Collection<?> c = (Collection<?>) o;
if (c.size() != size())
return false;
try {
return containsAll(c);
} catch (ClassCastException unused) {
return false;
} catch (NullPointerException unused) {
return false;
}
}
equals 方法只判断了同一个对象就返回true,从源代码可以看出来,存储自定义对象,并保证元素唯一性,必须重写hashCode 和equals 的方法
HashSet<Person> set =new HashSet<Person>();
set.add(new Person("张三",1));
set.add(new Person("张三",1));
set.add(new Person("李四",2));
set.add(new Person("李四",2));
for(Person person: set){
System.out.println("name="+person.getName()+",age="+person.getAge());
}
打印结果张三出现2次,李四出现2次
重写PersonhashCode 和eques的方法
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime*result+age;
result = prime*result+((name == null)?0:name.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if(this == obj)
return true;
if(obj == null)
return false;
if(!(obj instanceof Person))
return false;
Person other = (Person) obj;
if(age != other.age)
return false;
if(name == null){
if(other.name != null)
return false;
}else if(!name.equals(other.name))
return false;
return true;
}
网友评论