/* * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template */ package generics; import java.util.ArrayList; import java.util.Iterator; import java.util.List; /** * * @author steve */ public class GenericHashMap implements MinGenericMap { List> buckets = new ArrayList<>(); public GenericHashMap() { this(25); } public GenericHashMap(int n) { for(int i=0;i()); } } int hashToIndex(K k) { return Math.abs(k.hashCode()) % buckets.size(); } @Override public void put(K k, V v) { int index = hashToIndex(k); var bucket = buckets.get(index); bucket.put(k,v); } @Override public V get(K k) { int index = hashToIndex(k); var bucket = buckets.get(index); return bucket.get(k); } @Override public int size() { int sum=0; for(var bucket: buckets) { sum += bucket.size(); } return sum; } @Override public Iterator iterator() { return new Iterator() { Iterator> bucketIter = buckets.iterator(); Iterator iter = bucketIter.next().iterator(); @Override public boolean hasNext() { while(true) { if(iter.hasNext()) { return true; } else if(bucketIter.hasNext()) { iter = bucketIter.next().iterator(); } else { return false; } } } @Override public K next() { return iter.next(); } }; } public static void main(String[] args) { MinGenericMap map = new GenericHashMap<>(); GenericMapTest.test(map); } }