根据冲突解决的不同,可分为seperate chaining hash table, linear probing hash table, quadratic probing hash table.

 

自己实现的最简单饿 seperate chaining hash table。

package ADT;

import java.util.LinkedList;
/**
 * 自己实现的屌丝版的MySeperateChainingHashTable,
 * 
 * @author jd
 *
 * @param <K>
 * @param <V>
 */
public class MySeperateChainingHashTable<K, V> {
    private static int M = 10;
    private LinkedList<Entry<K, V>>[] items;

    public MySeperateChainingHashTable() {
        items = (LinkedList<Entry<K, V>>[]) (new LinkedList[M]);
        for (int i = 0; i < M; i++) {
            items[i] = new LinkedList<Entry<K, V>>();
        }
    }

    public void put(K key, V value) {
        int idx = hash(key);
        LinkedList<Entry<K, V>> list = items[idx];
        for (Entry<K, V> each : list) {
            if (each.key.equals(key)) {
                each.value = value;
                return;
            }
        }

        list.add(new Entry<K,V>(key, value));
    }

    public V get(K key) {
        int idx = hash(key);
        LinkedList<Entry<K, V>> list = items[idx];
        for (Entry<K, V> each : list) {
            if (each.key.equals(key)) {
                return each.value;
            }
        }

        return null;
    }

    private int hash(K key) {
        int res = key.hashCode();
        if (res < 0)
            res += M;
        return res % M;
    }

    private static class Entry<K, V> {
        public K key;
        public V value;

        public Entry(K key, V value) {
            this.key = key;
            this.value = value;
        }

    }

    public static void main(String[] args) {
        MySeperateChainingHashTable<Integer, String> hashtable = new MySeperateChainingHashTable<Integer, String>();

        for (int i = 0; i < 100; i++) {
            hashtable.put(i, i + "" + i);
        }

        for (int i = 0; i < 100; i++) {
            System.out.println(hashtable.get(i));
        }

    }

}
View Code

相关文章: