//: c17:dynatrash:DynaTrash.java // From Thinking in Java, 2nd Edition // Available at http://www.BruceEckel.com // (c) Bruce Eckel 1999 // Copyright notice in Copyright.txt // Using a HashMap of ArrayLists and RTTI // to automatically sort trash into // vectors. This solution, despite the // use of RTTI, is extensible. package c17.dynatrash; import c17.trash.*; import java.util.*; // Generic TypeMap works in any situation: class TypeMap { private HashMap t = new HashMap(); public void add(Object o) { Class type = o.getClass(); if(t.containsKey(type)) ((ArrayList)t.get(type)).add(o); else { ArrayList v = new ArrayList(); v.add(o); t.put(type,v); } } public ArrayList get(Class type) { return (ArrayList)t.get(type); } public Iterator keys() { return t.keySet().iterator(); } // Returns handle to adapter class to allow // callbacks from ParseTrash.fillBin(): public Fillable filler() { // Anonymous inner class: return new Fillable() { public void addTrash(Trash t) { add(t); } }; } } public class DynaTrash { public static void main(String[] args) { TypeMap bin = new TypeMap(); ParseTrash.fillBin("Trash.dat",bin.filler()); Iterator keys = bin.keys(); while(keys.hasNext()) Trash.sumValue( bin.get((Class)keys.next())); } } ///:~