基于散列实现的HashMap

public class SimpleHashMap {
    static final int SIZE = 997;
    static class MapEntry implements Map.Entry {

        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>[] 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> bucket = buckets[index];
        if(findEntry(bucket.listIterator(), key) == null) {
            bucket.add(new MapEntry(key, value));
            size ++;
        }
        
    }

    private int hashIndexOf(K key) {
        Objects.requireNonNull(key);
        return Math.abs(key.hashCode()) % SIZE;
    }

    private MapEntry findEntry(Iterator> iterator, K key) {
        while(iterator.hasNext()) {
            MapEntry oldMapEntry = iterator.next();
            if(oldMapEntry.getKey().equals(key)) {
                return oldMapEntry;
            }
        }
        return null;
    }

    public V get(K key) {
        ListIterator> iterator = buckets[hashIndexOf(key)].listIterator();
        return findEntry(iterator, key).getValue();
    }

    public int size() {
        return size;
    }
}

你可能感兴趣的:(基于散列实现的HashMap)