Hashset as HashMap addメソッド

5630 ワード

public class MapTest {
 public static void main(String[] args) {
  Map m =new HashMap();
  m.put("1", 2);
  Object i  = m.get("1");
  System.out.println(m.put("1", 3));
  System.out.println(m.get("1"));
  
  Set set = new HashSet();
  System.out.println(set.add("5"));
  System.out.println(set.add("5"));
  
  List li = new ArrayList();
  set.add("6");
  System.out.println(set.add("6"));
  System.out.println("----set size ---  "+set.size());

結果:
23truefalsefalse----set size ---  2
まずhashsetの構造方法を見てみましょう
    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);
    }

hashsetは実はhashMapであることがわかります
addメソッドを見て
 
   public boolean add(E e) {
	return map.put(e, PRESENT)==null;
    }

hashmapのaddメソッドを呼び出してhshmapのputメソッドを見ています

   public V put(K key, V value) {
        if (key == null)
            return putForNullKey(value);
        int hash = hash(key.hashCode());// hash key table 
        int i = indexFor(hash, table.length);// hash table 
        for (Entry<K,V> e = table[i]; e != null; e = e.next) {
            Object k;
            // key hashcode    table i Entry key 
            if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
                V oldValue = e.value;
                e.value = value;// 。 key value,System.out.println(m.get("1")); 3
                e.recordAccess(this);
                return oldValue;// key value 。 System.out.println(m.put("1", 3)); 2
                /*  set value PRESENT  set key , key value, PRESENT ,
                  System.out.println(set.add("6")); PRESENT == null  false
                   public boolean add(E e) {
                    private static final Object PRESENT = new Object();
             return map.put(e, PRESENT)==null;//PRESENT 
                    }
                */
            }
        }
        modCount++;
        addEntry(hash, key, value, i);
        return null;// , set key 。 map.put(e, PRESENT)==null true
    }