标签:div java基础 get int move java rem obj private
对于HashSet而言,它是基于HashMap实现的,底层采用HashMap来保存元素的。今天我们就简单的分析一下它的实现。
public class HashSet<E> extends AbstractSet<E> implements Set<E>, Cloneable, java.io.Serializable private transient HashMap<E,Object> map; // Dummy value to associate with an Object in the backing Map private static final Object PRESENT = new Object();
hashSet的构造方法,是创建一个hashMap。
public HashSet() { map = new HashMap<>(); }
public Iterator<E> iterator() { return map.keySet().iterator(); } public int size() { return map.size(); } public boolean isEmpty() { return map.isEmpty(); } public boolean contains(Object o) { return map.containsKey(o); } public boolean add(E e) { return map.put(e, PRESENT)==null; // PRESENT是hashSet的成员变量 } public boolean remove(Object o) { return map.remove(o)==PRESENT; // PRESENT是hashSet的成员变量 } public void clear() { map.clear(); }
标签:div java基础 get int move java rem obj private
原文地址:http://www.cnblogs.com/huhx/p/baseusejavahashset1.html