首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 软件管理 > 软件架构设计 >

java从写哈希表

2012-06-29 
java自写哈希表hash表中的元素:public class ItemK, V{private K keyprivate V valuepublic Item(K ke

java自写哈希表
hash表中的元素:


public class Item<K, V>{private K key;private V value;public Item(K key, V value){this.key = key;this.value = value;}public K getKey(){return key;}public void setKey(K key){this.key = key;}public V getValue(){return value;}public void setValue(V value){this.value = value;}@Overridepublic int hashCode(){return key.hashCode();}}


hash表实现:

public class HashTable<K, V>{private Item<K, V>[] items;private int len;public HashTable(int size){this.items = new Item[size];this.len = items.length;}public V put(K key, V value){int hashAddr = key.hashCode() % len;Item<K, V> item = new Item<K, V>(key, value);if (items[hashAddr] == null){items[hashAddr] = item;return null;} else{int i = 0;for (; items[(hashAddr + i) % len] != null; i++){// 取得当前元素Item<K, V> curr = items[(hashAddr + i) % len];// 替换if (curr.getKey().equals(key)){V result = curr.getValue();items[(hashAddr + i) % len] = item;return result;} else{// 已经走了一圈,退出if ((hashAddr + i + 1) % items.length == hashAddr){System.out.println("空间已满,【" + item.getKey() + "," + item.getValue() + "】 插入失败!");return null;}}}items[(hashAddr + i) % items.length] = item;return null;}}public V get(K key){int hashAddr = key.hashCode() % len;for (int i = 0; items[(hashAddr + i) % items.length] != null; i++){// 取得当前元素Item<K, V> curr = items[(hashAddr + i) % len];if (curr.getKey().equals(key)){return curr.getValue();} else if ((hashAddr + i + 1) % items.length == hashAddr){System.out.println("找了一圈未找到");return null;}}return null;}public V remove(K key){int hashAddr = key.hashCode() % len;for (int i = 0; items[(hashAddr + i) % items.length] != null; i++){// 取得当前元素Item<K, V> curr = items[(hashAddr + i) % len];if (curr.getKey().equals(key)){items[(hashAddr + i) % len] = null;return curr.getValue();} else if ((hashAddr + i + 1) % items.length == hashAddr){System.out.println("找了一圈未找到");return null;}}return null;}public static void main(String[] args){HashTable<String, String> h = new HashTable<String, String>(5);System.out.println(h.put("a", "测试a"));System.out.println(h.put("a", "测试b"));System.out.println(h.put("e", "测试e"));System.out.println("-----------------------------");System.out.println(h.remove("a"));System.out.println(h.get("a"));    System.out.println(h.get("e"));}}


热点排行