简单hashmap实现
Posted bloch
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了简单hashmap实现相关的知识,希望对你有一定的参考价值。
学习于java编程思想
1 import java.io.Serializable; 2 import java.util.*; 3 4 /** 5 * 简单散列Map 6 * 7 * @param <K> 8 * @param <V> 9 */ 10 public class SimpleHashMap<K, V> extends AbstractMap<K, V> implements Serializable { 11 private static final long serialVersionUID = -7250646258928392838L; 12 static final int SIZE = 997; 13 14 LinkedList<MapEntry<K, V>>[] buckets = new LinkedList[SIZE]; 15 16 @Override 17 public V get(Object key) { 18 int index = Math.abs(key.hashCode()) % SIZE; 19 if (buckets[index] == null) { 20 return null; 21 } 22 for (MapEntry<K, V> iPair : buckets[index]) { 23 if (iPair.getKey().equals(key)) { 24 return iPair.getValue(); 25 } 26 } 27 return null; 28 } 29 30 @Override 31 public V put(K key, V value) { 32 V oldValue = null; 33 int index = Math.abs(key.hashCode()) % SIZE; 34 if (buckets[index] == null) { 35 buckets[index] = new LinkedList<>(); 36 } 37 LinkedList<MapEntry<K, V>> bucket = buckets[index]; 38 MapEntry<K, V> pair = new MapEntry<>(key, value); 39 boolean found = false; 40 ListIterator<MapEntry<K, V>> it = bucket.listIterator(); 41 while (it.hasNext()) { 42 MapEntry<K, V> iPair = it.next(); 43 if (iPair.getKey().equals(key)) { 44 oldValue = iPair.getValue(); 45 it.set(pair); 46 found = true; 47 break; 48 } 49 } 50 if (!found) { 51 buckets[index].add(pair); 52 } 53 54 return oldValue; 55 } 56 57 @Override 58 public Set<Entry<K, V>> entrySet() { 59 Set<Entry<K, V>> set = new HashSet<>(); 60 for (LinkedList<MapEntry<K, V>> bucket : buckets) { 61 if (bucket == null) { 62 continue; 63 } 64 for (MapEntry<K, V> mpair : bucket) { 65 set.add(mpair); 66 } 67 } 68 return set; 69 } 70 71 public static void main(String[] args) { 72 Map<String, String> map = new SimpleHashMap<>(); 73 map.put("a", "32"); 74 System.out.println(map.get("a")); 75 } 76 77 static class MapEntry<K, V> implements Entry<K, V> { 78 private K key; 79 private V value; 80 81 public MapEntry(K key, V value) { 82 this.key = key; 83 this.value = value; 84 } 85 86 @Override 87 public K getKey() { 88 return key; 89 } 90 91 @Override 92 public V getValue() { 93 return value; 94 } 95 96 @Override 97 public V setValue(V v) { 98 V result = value; 99 value = v; 100 return result; 101 } 102 103 @Override 104 public int hashCode() { 105 return (key == null ? 0 : key.hashCode()) ^ (value == null ? 0 : value.hashCode()); 106 } 107 108 @Override 109 public boolean equals(Object o) { 110 if (!(o instanceof MapEntry)) { 111 return false; 112 } 113 MapEntry me = (MapEntry) o; 114 return (key == null ? me.getKey() == null : key.equals(me.getKey())) 115 && (value == null ? me.getValue() == null : value.equals(me.getValue())); 116 } 117 118 @Override 119 public String toString() { 120 return key + "=" + value; 121 } 122 } 123 }
以上是关于简单hashmap实现的主要内容,如果未能解决你的问题,请参考以下文章
Java集合相关学习——手写一个简单的Map接口实现类(HashMap)
Java集合相关学习——手写一个简单的Map接口实现类(HashMap)