52 lines
1.2 KiB
Java
Raw Normal View History

2015-05-06 15:14:33 -07:00
//: patterns/dynatrash/DynaTrash.java
2015-05-18 23:05:20 -07:00
// Using a Map of Lists and RTTI
2015-05-05 11:20:13 -07:00
// to automatically sort trash into
// vectors. This solution, despite the
// use of RTTI, is extensible.
package patterns.dynatrash;
import patterns.trash.*;
import java.util.*;
// Generic TypeMap works in any situation:
2015-05-06 15:14:33 -07:00
class TypeMap<T> {
private Map<Class,List<T>> t = new HashMap<>();
public void add(T o) {
2015-05-05 11:20:13 -07:00
Class type = o.getClass();
if(t.containsKey(type))
2015-05-06 15:14:33 -07:00
t.get(type).add(o);
2015-05-05 11:20:13 -07:00
else {
2015-05-06 15:14:33 -07:00
List<T> v = new ArrayList<>();
2015-05-05 11:20:13 -07:00
v.add(o);
t.put(type,v);
}
}
2015-05-06 15:14:33 -07:00
public List<T> get(Class type) {
return t.get(type);
2015-05-05 11:20:13 -07:00
}
2015-05-06 15:14:33 -07:00
public Iterator<Class> keys() {
return t.keySet().iterator();
2015-05-05 11:20:13 -07:00
}
}
// Adapter class to allow
// callbacks from ParseTrash.fillBin():
class TypeMapAdapter implements Fillable {
2015-05-06 15:14:33 -07:00
TypeMap<Trash> map;
public TypeMapAdapter(TypeMap<Trash> tm) {
map = tm;
}
2015-05-05 11:20:13 -07:00
@Override
public void addTrash(Trash t) { map.add(t); }
}
public class DynaTrash {
public static void main(String[] args) {
2015-05-06 15:14:33 -07:00
TypeMap<Trash> bin = new TypeMap<>();
ParseTrash.fillBin("Trash.dat",
2015-05-05 11:20:13 -07:00
new TypeMapAdapter(bin));
2015-05-06 15:14:33 -07:00
Iterator<Class> keys = bin.keys();
2015-05-05 11:20:13 -07:00
while(keys.hasNext())
2015-05-06 15:14:33 -07:00
Trash.sumValue(bin.get(keys.next()));
2015-05-05 11:20:13 -07:00
}
} ///:~