58 lines
1.5 KiB
Java
Raw Normal View History

2015-05-05 11:20:13 -07:00
//: patterns/recycleb/RecycleB.java
// Adding more objects to the recycling problem.
package patterns.recycleb;
import patterns.trash.*;
import java.util.*;
2015-05-27 23:30:19 -07:00
// A List that admits only the right type:
class Tbin<T extends Trash> extends ArrayList<T> {
Class<T> binType;
Tbin(Class<T> type) {
binType = type;
2015-05-05 11:20:13 -07:00
}
2015-05-27 23:30:19 -07:00
@SuppressWarnings("unchecked")
boolean grab(Trash t) {
2015-05-05 11:20:13 -07:00
// Comparing class types:
if(t.getClass().equals(binType)) {
2015-05-27 23:30:19 -07:00
add((T)t); // Downcast to this TBin's type
2015-05-05 11:20:13 -07:00
return true; // Object grabbed
}
return false; // Object not grabbed
}
}
2015-05-27 23:30:19 -07:00
class TbinList<T extends Trash>
extends ArrayList<Tbin<? extends T>> { // (1)
boolean sort(T t) {
for(Tbin<? extends T> ts : this)
if(ts.grab(t))
return true;
2015-05-05 11:20:13 -07:00
return false; // bin not found for t
}
2015-05-27 23:30:19 -07:00
void sortBin(Tbin<T> bin) { // (2)
for(T aBin : bin)
if(!sort(aBin))
System.err.println("Bin not found");
2015-05-05 11:20:13 -07:00
}
}
public class RecycleB {
2015-05-27 23:30:19 -07:00
static Tbin<Trash> bin = new Tbin<>(Trash.class);
2015-05-05 11:20:13 -07:00
public static void main(String[] args) {
// Fill up the Trash bin:
ParseTrash.fillBin("Trash.dat", bin);
2015-05-27 23:30:19 -07:00
TbinList<Trash> trashBins = new TbinList<>();
trashBins.add(new Tbin<>(Aluminum.class));
trashBins.add(new Tbin<>(Paper.class));
trashBins.add(new Tbin<>(Glass.class));
// add one line here: (3)
trashBins.add(new Tbin<>(Cardboard.class));
2015-05-05 11:20:13 -07:00
2015-05-27 23:30:19 -07:00
trashBins.sortBin(bin); // (4)
2015-05-05 11:20:13 -07:00
2015-05-27 23:30:19 -07:00
trashBins.forEach(Trash::sumValue);
2015-05-05 11:20:13 -07:00
Trash.sumValue(bin);
}
} ///:~