HashTable学习1

来源:互联网 发布:证件照自拍软件 编辑:程序博客网 时间:2024/06/08 01:14

下面文章转自: http://hi.baidu.com/onlylamplight/blog/item/b57bbb5536ce215f574e0007.html

 

今天看了HashTable的源码,就把学习记下来了,怕忘记。

在看HashTable的适合我看到在HashTable的内部定义了一个内部静态类,也可以说是一个数据结构吧,

private static class Entry<K,V> implements Map.Entry<K,V> {

    int hash;   //hash

    K key;       //hash值的KEY

    V value;     //存储的值

    Entry<K,V> next; //下一个节点的位置

HashTable的写入来看看HashTable的内部存储结构,

public synchronized V put(K key, V value) {

    // Make sure the value is not null

    if (value == null) {

        throw new NullPointerException();

    }

 

    // Makes sure the key is not already in the hashtable.

    Entry tab[] = table; //table是存储原HashTable中元素的数组

    int hash = key.hashCode();

    int index = (hash & 0x7FFFFFFF) % tab.length;

     //在这个数据结构中定义了链表的结构,在查找的时候按照链表来查找和遍历

    for (Entry<K,V> e = tab[index] ; e != null ; e = e.next) {

        if ((e.hash == hash) && e.key.equals(key)) {

            V old = e.value;

            e.value = value;

            return old;

        }

    }

 

    modCount++;

    if (count >= threshold) {

        // Rehash the table if the threshold is exceeded

        rehash();

            tab = table;

            index = (hash & 0x7FFFFFFF) % tab.length;

    }

 

    // Creates the new entry.

    Entry<K,V> e = tab[index];

    tab[index] = new Entry<K,V>(hash, key, value, e);

    count++;

    return null;

    }

从上面的代码可以看到,HashTable在内部定义的数据结果是一个链表的数据结构,应为他保存了下一个节点的,而在这些节点的存储上,他又是以数组的形式存储的。在数组的下标用KeyHash码做数学运算来做下标,这样可以快速的通过Key来找到相关的value

 

而在Hash的迭代上,看看他们是怎么循环的:

HashTable的遍历上一般有两种方法: