实现HashTable
来源:互联网 发布:curl 发送json数据 编辑:程序博客网 时间:2024/05/17 23:50
完全不是当年考研中数据结构里的hash表,当时书中只说如何存放,冲突怎么处理,一直以为存的就是一个元素,后来一想get时输入什么呢,一看jdk源码才知道,原来存的是键值对,是两个元素,与HashMap相似!!看来不能读死书啊,要活学活用!
/** * Title: HashTableCuston * Description: * * @date 2017/12/24 18:51 */public class HashTableCuston<K, V> { private Entry<?, ?>[] table; private int capacity; public HashTableCuston() {//默认构造函数,暂时未加入装载因子,未完待续 this(11); } public HashTableCuston(int capacity) { if(capacity < 0){ throw new IllegalArgumentException("Illegal capacity :"+capacity); } this.capacity = capacity; table = new Entry<?, ?>[capacity]; } private static class Entry<K, V> { int hash; K key; V value; Entry<K, V> next; public Entry(int hash, K key, V value, Entry<K, V> next) { this.hash = hash; this.key = key; this.value = value; this.next = next; } public K getKey() { return key; } public V getValue() { return value; } }//Entry /** * 根据key获取value * @param key * @return */ public synchronized V get(Object key){ Entry<?,?>[] tab = table; int hash = key.hashCode() & 0X7FFFFFF ; int index = hash % table.length; for(Entry<?,?> entry = tab[index];entry != null ;entry = entry.next ){ if( (entry.hash == hash) && (entry.key == entry.key) ){ return (V)entry.value; } } return null; } /** * 放入键值对 * * @param key * @param value * @return */ public synchronized V put(K key, V value) { Entry<?, ?>[] tab = table;//Entry<?, ?>是Entry<String, Integer>等具体类的父类 int hash = key.hashCode(); int index = (hash & 0X7FFFFFF) % tab.length; Entry<K, V> entry = (Entry<K, V>) tab[index]; //检查有无已存在的key for (; entry != null; entry = entry.next) { if ((entry.hash == hash) && entry.key == key) { V oldValue = entry.value; entry.value = value; return oldValue; } } addEntry(hash, key, value, index); return null; } /** * 创建新的结点 * * @param hash * @param key * @param value * @param index */ private void addEntry(int hash, K key, V value, int index) { Entry<?, ?>[] tab = table; Entry<K, V> entry = (Entry<K, V>) tab[index];//之前已存在结点 tab[index] = new Entry<>(hash, key, value, entry);//之前已存在的结点作为后继结点 }}
public static void main(String[] args) { HashTableCuston<String, Integer> hashtable = new HashTableCuston<String, Integer>(5); hashtable.put("one", 1); hashtable.put("two", 2); hashtable.put("three", 3); hashtable.put("four", 4); hashtable.put("five", 5); hashtable.put("six", 6); hashtable.put("seven", 7); Integer v = hashtable.get("six");//输出6 System.out.println(v); }
阅读全文