HashSet 是用Map实现的,向set添加元素,其实就是向内部的map添加一个Key,即添加的元素作为key,而值为一个静态Object对象,即所有 的key都映射到该对象上,set的删除调用了额 map.remove(key),如果key存在 则返回真,否则返回假- public class HashSet<E> extends AbstractSet<E> implements Set<E>, Cloneable,
- java.io.Serializable {
- static final long serialVersionUID = -5024744406713321676L;
- private transient HashMap<E, Object> map;
- private static final Object PRESENT = new Object();
- public boolean add(E e) {
- return map.put(e, PRESENT) == null;
- }
- public boolean remove(Object o) {
- return map.remove(o) == PRESENT;
- }
- }
复制代码
|
|