public class SimpleHashMap<K, V> {
static final int SIZE = 997;
static class MapEntry<K, V> implements Map.Entry<K, V> {
private final K key;
private V value;
public MapEntry(K key, V value) {
this.key = key;
this.value = value;
}
@Override
public K getKey() {
return key;
}
@Override
public V getValue() {
return value;
}
@Override
public V setValue(V value) {
this.value = value;
return value;
}
}
@SuppressWarnings("unchecked")
LinkedList<MapEntry<K, V>>[] buckets = new LinkedList[SIZE];
private int size;
public void put(K key, V value) {
int index = hashIndexOf(key);
if(buckets[index] == null)
buckets[index] = new LinkedList<>();
LinkedList<MapEntry<K, V>> bucket = buckets[index];
if(findEntry(bucket.listIterator(), key) == null) {
bucket.add(new MapEntry<K, V>(key, value));
size ++;
}
}
private int hashIndexOf(K key) {
Objects.requireNonNull(key);
return Math.abs(key.hashCode()) % SIZE;
}
private MapEntry<K, V> findEntry(Iterator<MapEntry<K, V>> iterator, K key) {
while(iterator.hasNext()) {
MapEntry<K, V> oldMapEntry = iterator.next();
if(oldMapEntry.getKey().equals(key)) {
return oldMapEntry;
}
}
return null;
}
public V get(K key) {
ListIterator<MapEntry<K, V>> iterator = buckets[hashIndexOf(key)].listIterator();
return findEntry(iterator, key).getValue();
}
public int size() {
return size;
}
}
基于散列实现的HashMap
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
相关阅读更多精彩内容
- 众所周知,使用Java的HashMap数据结构时,要求正确实现hashCode(),但是为什么呢?hashCode...
- 基于:密码散列PBKDF2的用户密码加密 为什么需要把应用程序中用户的密码进行散列化? 当设计一个需要接受用户密码...