HasMap简单实现

来源:互联网 发布:maven nexus windows 编辑:程序博客网 时间:2024/06/01 09:06

采用链接法处理碰撞

/** * MapEntry<K,V>存储KEY-VALUE键值对,当发生碰撞时,可以还可以根据不同的key来查找value。 *  * @author Administrator * * @param <K> * @param <V> */class MapEntry<K, V> {private K key;   //键private V value; //值public MapEntry(K key, V value) {super();this.key = key;this.value = value;}public boolean equivalent(MapEntry<K, V> entry) {return equivalent(entry.getKey());}public boolean equivalent(K k) {return key.equals(k);}public K getKey() {return key;}public V getValue() {return value;}}/** * 设计并实现散列表,使用链表处理碰撞冲突 *  * @author Administrator * * @param <K> * @param <V> */public class Hash<K, V> {private final int MAX_SIZE = 10;private LinkedList<MapEntry<K, V>>[] items;@SuppressWarnings("unchecked")public Hash() {items = (LinkedList<MapEntry<K, V>>[]) new LinkedList[MAX_SIZE];}/** * 非常简单的散列,可以导致许多碰撞冲突。 * @param key * @return */public int hashCodeOfKey(K key) {return key.toString().length() % items.length;}public void put(K key, V value) {int idx = hashCodeOfKey(key);if (items[idx] == null) {items[idx] = new LinkedList<MapEntry<K, V>>();}LinkedList<MapEntry<K, V>> list = items[idx];for (MapEntry<K, V> entry : list) {//遍历链表发现是否有相同的keyif (entry.equivalent(key)) {list.remove(entry);break;}}MapEntry<K, V> entry = new MapEntry<K, V>(key, value);list.add(entry);}public V get(K key) {int idx = hashCodeOfKey(key);if (items[idx] == null) {return null;}LinkedList<MapEntry<K, V>> list = items[idx];for (MapEntry<K, V> entry : list) {if (entry.equivalent(key)) {return entry.getValue();}}return null;}public static void main(String[] args) {Hash<String, String> hash = new Hash<String, String>();hash.put("zdm", "帥");hash.put("zzm", "丑");hash.put("zzm", "呵呵");System.out.println(hash.get("zdm"));System.out.println(hash.get("zzm"));}}


0 0
原创粉丝点击