Hashset as HashMap add方法

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());

  结果:

2
3
true
false
false
----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
    }

  

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值