//: c08:AssocArray.java // From Thinking in Java, 2nd Edition // Available at http://www.BruceEckel.com // (c) Bruce Eckel 1999 // Copyright notice in Copyright.txt // Simple version of a Map import java.util.*; public class AssocArray extends AbstractMap { private ArrayList keys = new ArrayList(); private ArrayList values = new ArrayList(); public int size() { return keys.size(); } public boolean isEmpty() { return keys.isEmpty(); } public Object put(Object key, Object value) { int index = keys.indexOf(key); if (index == -1) { // Key not found keys.add(key); values.add(value); return null; } else { // Key already in table; replace Object returnval = values.get(index); values.set(index, value); return returnval; } } public Object get(Object key) { int index = keys.indexOf(key); // indexOf() Returns -1 if key not found: if(index == -1) return null; return values.get(index); } public Object remove(Object key) { int index = keys.indexOf(key); if(index == -1) return null; keys.remove(index); Object returnval = values.get(index); values.remove(index); return returnval; } public Set keySet() { return new HashSet(keys); } public Collection values() { return values; } public Set entrySet() { Set set = new HashSet(); // Iterator it = keys.iterator(); // while(it.hasNext()) { // Object k = it.next(); // Object v = values.get(values.indexOf(k)); // set.add(new Map.Entry(k, v)); // } return set; } // Test it: public static void main(String[] args) { AssocArray aa = new AssocArray(); for(char c = 'a'; c <= 'z'; c++) aa.put(String.valueOf(c), String.valueOf(c) .toUpperCase()); char[] ca = { 'a', 'e', 'i', 'o', 'u' }; for(int i = 0; i < ca.length; i++) System.out.println("Uppercase: " + aa.get(String.valueOf(ca[i]))); } } ///:~