美文网首页
基于散列实现的HashMap

基于散列实现的HashMap

作者: 业余的猫 | 来源:发表于2017-04-10 20:52 被阅读0次
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

      本文链接:https://www.haomeiwen.com/subject/mzseattx.html