基本知识
- 源码:
public class HashSet<E>
extends AbstractSet<E>
implements Set<E>, Cloneable, java.io.Serializable
{
private transient HashMap<E,Object> map; // 基于HashMap实现
// Dummy value to associate with an Object in the backing Map
private static final Object PRESENT = new Object(); // 作为map的value值,因为set只有key没有value
public HashSet() {
map = new HashMap<>();
}
public boolean add(E e) {
// new added: true
// already existed: false
return map.put(e, PRESENT)==null;
}
}
- 允许null元素
HashSet aSet = new HashSet();
aSet.add("a");
aSet.add("b");
aSet.add("a");
aSet.add(null);
- 元素无序
- 不线程安全:多个线程同时修改时不保证结果
定义HashSet不定义元素类型会怎么样?
HashSet aSet = new HashSet();
aSet.add("a");
aSet.add(null);
aSet.add(0); // 不会报错
定义了元素类型的话就会编译错误

HashSet子类依靠什么方法区分重复元素?
hashCode(), equals()
当在HashSet中新增一个值时,先hashCode()看是否已存在相同hashCode, 如果存在,则再用equals判断值是否相等。
How HashSet Maintains Uniqueness?
When we put an object into a HashSet, it uses the object’s hashcode value to determine if an element is not in the set already.
Each hash code value corresponds to a certain bucket location which can contain various elements, for which the calculated hash value is the same. But two objects with the same hashCode might not be equal.
So, objects within the same bucket will be compared using the equals() method.
HashSet基于HashMap实现元素唯一性,添加对象时通过hashCode()确定桶位置,若存在冲突,则使用equals()方法判断对象是否相等。允许存储null元素,但不保证元素顺序且非线程安全。

被折叠的 条评论
为什么被折叠?



