import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.NoSuchElementException; public class UnsortedMap extends AbstractMap { private ArrayList> entryList; public UnsortedMap() { entryList = new ArrayList<>(); } @Override public int size() { return entryList.size(); } @Override public void clear() { entryList.clear(); } private int findKeyIndex(K key) { int idx=0; for (Entry e : entryList) { if (e.getKey().equals(key)) return idx; idx++; } return -1; } @Override public boolean containsKey(K key) { return findKeyIndex(key) >= 0; } private int findValueIndex(V value) { int idx=0; for (Entry e : entryList) { if (e.getValue().equals(value)) return idx; idx++; } return -1; } @Override public boolean containsValue(V value) { return findValueIndex(value) >= 0; } @Override public V get(K key) { int idx = findKeyIndex(key); return (idx<0) ? null : entryList.get(idx).getValue(); } @Override public V put(K key, V value) { V v = remove(key); entryList.add(new Entry(key, value)); return v; } @Override public V remove(K key) { int idx = findKeyIndex(key); V v=null; if (idx>=0) { v = entryList.get(idx).getValue(); entryList.remove(idx); } return v; } private class EntryIterator implements Iterator> { int idx=0; public boolean hasNext() { return idx next() { if (idx>=entryList.size()) throw new NoSuchElementException(); return entryList.get(idx++); } public void remove(K key) { throw new UnsupportedOperationException(); } } private class EntryIterable implements Iterable> { public Iterator> iterator() { return new EntryIterator(); } } @Override public Iterable> entrySet() { return new EntryIterable(); } public void doExample() { HashMap m = new HashMap<>(); System.out.println(m.isEmpty() + " " + m.toString()); System.out.println(m.put(5,"A") + " " + m.toString()); System.out.println(m.put(7,"B") + " " + m.toString()); System.out.println(m.put(2,"E") + " " + m.toString()); System.out.println(m.put(8,"A") + " " + m.toString()); System.out.println(m.put(2,"Q") + " " + m.toString()); System.out.println(m.get(7) + " " + m.toString()); System.out.println(m.get(4) + " " + m.toString()); System.out.println(m.remove(2) + " " + m.toString()); System.out.println(m.remove(5) + " " + m.toString()); System.out.println(m.isEmpty() + " " + m.toString()); System.out.println(m.entrySet() + " " + m.toString()); System.out.println(m.values() + " " + m.toString()); } public static void main(String[] args) { (new UnsortedMap()).doExample(); } }