ITeye博客

HashMap,set??

mlaaalm · 2010-06-19 22:18 · Collection · 非技术 · 算法 · Markdown

 /*
 hashMap明显维护了一个数组
数组下标就是利用hashCode的值加上适当算法得到的
*/

transient Entry[] table;

/*
两个不同对象他们的hashCode可能相等,也就是保存在同一个table[hashcode]中
这种情况下,看到Entry同时保存了next这个指针
*/

static class Entry<K,V> implements Map.Entry<K,V> {
        final K key;
        V value;
        final int hash;
        Entry<K,V> next;

        /**
         * Create new entry.
         */
        Entry(int h, K k, V v, Entry<K,V> n) {
            value = v;
            next = n;
            key = k;
            hash = h;
        }


/*
下标i是根据hash算法
*/
public V put(K key, V value) {
	K k = maskNull(key);
        int hash = hash(k);
        int i = indexFor(hash, table.length);

        for (Entry<K,V> e = table[i]; e != null; e = e.next) {
////hash一样&&equals is true 才是同样的对象(key)
            if (e.hash == hash && eq(k, e.key)) {
                V oldValue = e.value;
                e.value = value;
                e.recordAccess(this);
                return oldValue;
            }
        }

        modCount++;
        addEntry(hash, k, value, i);
        return null;
    }

//eq method
 static boolean eq(Object x, Object y) {
        return x == y || x.equals(y);
    }

 

 

 

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

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。