如图,是Hashtable采用的链表式的结构,即键值冲突的时候直接加到此键值对应的链表后面。下面提供一个简单的Java类的实现。
- public class HashTableDef {
- private int capacity = 1000;// 非重复的键值个数,即键值从0-999,可以在初始话的时候指定
- private Map[] keys;// 存放键值所对应的key-value对
- /**
- * 默认容量的构造函数,默认容量为1000
- */
- public HashTableDef() {
- keys = new Map[capacity];
- for (int i = 0; i < capacity; i++) {
- keys[i] = null;
- }
- }
- /**
- * 带容量的构造函数
- *
- * @param cy
- */
- public HashTableDef(int cy) {
- this.capacity = cy;
- keys = new Map[this.capacity];
- for (int i = 0; i < capacity; i++) {
- keys[i] = null;
- }
- }
- /**
- * 把键值对key-value放到hash表中
- *
- * @param key
- * @param value
- */
- public void put(Object key, Object value) {
- int keyIndex = key.hashCode() % capacity;// 得到此键对应的键值
- boolean isSameKey = false;
- Map map = new Map();
- map.key = key;
- map.value = value;
- Map currentMap = keys[keyIndex], prevMap = null;
- if (currentMap == null) {
- // 当前键值没有冲突,
- keys[keyIndex] = map;
- System.out.println("直接放入到hashtable中" + keys[keyIndex] + " "
- + currentMap);
- } else {
- // 处理键值冲突,放到此键值对应的链表的最后
- while (currentMap != null) {
- // 不光是键值冲突,而且键相等,此时此时覆盖以前的键对应的键值
- if (currentMap.key.equals(key) || currentMap.key == key) {
- currentMap.value = value;
- isSameKey = true;
- System.out.println("出现了同名的Key:" + key);
- break;
- }
- prevMap = currentMap;
- currentMap = currentMap.next;
- }
- if (isSameKey == false) {
- System.out.println("放到链表中");
- prevMap.next = map;
- }
- }
- }
- /**
- * 给定键值,取得此键值对应的Value,如果没有,返回null
- *
- * @param key
- * 键值
- * @return
- */
- public Object get(Object key) {
- int keyIndex = key.hashCode() % capacity;// 得到此键对应的键值
- Map currentMap = keys[keyIndex];
- // 遍历此键值对应的入口链表
- while (currentMap != null) {
- // 出现相等的键,则返回
- if (currentMap.key.equals(key) || currentMap.key == key) {
- return currentMap.value;
- }
- currentMap = currentMap.next;
- }
- return null;
- }
- private class Map {
- public Object key;
- public Object value;
- public Map next = null;
- }
- }