hashSet源码,楼主的想法是对的:- 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;
- // Dummy value to associate with an Object in the backing Map
- private static final Object PRESENT = new Object();
- /**
- * Constructs a new, empty set; the backing <tt>HashMap</tt> instance has
- * default initial capacity (16) and load factor (0.75).
- */
- public HashSet() {
- map = new HashMap<E,Object>();
- }
- /**
- * Constructs a new set containing the elements in the specified
- * collection. The <tt>HashMap</tt> is created with default load factor
- * (0.75) and an initial capacity sufficient to contain the elements in
- * the specified collection.
- *
- * @param c the collection whose elements are to be placed into this set
- * @throws NullPointerException if the specified collection is null
- */
- public HashSet(Collection<? extends E> c) {
- map = new HashMap<E,Object>(Math.max((int) (c.size()/.75f) + 1, 16));
- addAll(c);
- }
- /**
- * Constructs a new, empty set; the backing <tt>HashMap</tt> instance has
- * the specified initial capacity and the specified load factor.
- *
- * @param initialCapacity the initial capacity of the hash map
- * @param loadFactor the load factor of the hash map
- * @throws IllegalArgumentException if the initial capacity is less
- * than zero, or if the load factor is nonpositive
- */
- public HashSet(int initialCapacity, float loadFactor) {
- map = new HashMap<E,Object>(initialCapacity, loadFactor);
- }
- /**
- * Constructs a new, empty set; the backing <tt>HashMap</tt> instance has
- * the specified initial capacity and default load factor (0.75).
- *
- * @param initialCapacity the initial capacity of the hash table
- * @throws IllegalArgumentException if the initial capacity is less
- * than zero
- */
- public HashSet(int initialCapacity) {
- map = new HashMap<E,Object>(initialCapacity);
- }
- /**
- * Constructs a new, empty linked hash set. (This package private
- * constructor is only used by LinkedHashSet.) The backing
- * HashMap instance is a LinkedHashMap with the specified initial
- * capacity and the specified load factor.
- *
- * @param initialCapacity the initial capacity of the hash map
- * @param loadFactor the load factor of the hash map
- * @param dummy ignored (distinguishes this
- * constructor from other int, float constructor.)
- * @throws IllegalArgumentException if the initial capacity is less
- * than zero, or if the load factor is nonpositive
- */
- HashSet(int initialCapacity, float loadFactor, boolean dummy) {
- map = new LinkedHashMap<E,Object>(initialCapacity, loadFactor);
- }
复制代码 |