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.*;
|
|
|
|
|
|
|
|
// A vector that admits only the right type:
|
2015-05-18 23:05:20 -07:00
|
|
|
class Tbin<T> extends ArrayList<T> {
|
2015-05-05 11:20:13 -07:00
|
|
|
Class binType;
|
2015-05-18 23:05:20 -07:00
|
|
|
Tbin() {
|
|
|
|
this.binType = binType;
|
2015-05-05 11:20:13 -07:00
|
|
|
}
|
2015-05-18 23:05:20 -07:00
|
|
|
boolean grab(T t) {
|
2015-05-05 11:20:13 -07:00
|
|
|
// Comparing class types:
|
|
|
|
if(t.getClass().equals(binType)) {
|
|
|
|
add(t);
|
|
|
|
return true; // Object grabbed
|
|
|
|
}
|
|
|
|
return false; // Object not grabbed
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
class TbinList extends ArrayList { //(*1*)
|
2015-05-18 23:05:20 -07:00
|
|
|
@SuppressWarnings("unchecked")
|
2015-05-05 11:20:13 -07:00
|
|
|
boolean sort(Trash t) {
|
|
|
|
Iterator e = iterator();
|
|
|
|
while(e.hasNext()) {
|
|
|
|
Tbin bin = (Tbin)e.next();
|
|
|
|
if(bin.grab(t)) return true;
|
|
|
|
}
|
|
|
|
return false; // bin not found for t
|
|
|
|
}
|
|
|
|
void sortBin(Tbin bin) { // (*2*)
|
|
|
|
Iterator e = bin.iterator();
|
|
|
|
while(e.hasNext())
|
|
|
|
if(!sort((Trash)e.next()))
|
|
|
|
System.out.println("Bin not found");
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
public class RecycleB {
|
2015-05-18 23:05:20 -07:00
|
|
|
static Tbin<Trash> bin = new Tbin<>();
|
|
|
|
@SuppressWarnings("unchecked")
|
2015-05-05 11:20:13 -07:00
|
|
|
public static void main(String[] args) {
|
|
|
|
// Fill up the Trash bin:
|
|
|
|
ParseTrash.fillBin("Trash.dat", bin);
|
|
|
|
|
|
|
|
TbinList trashBins = new TbinList();
|
2015-05-18 23:05:20 -07:00
|
|
|
trashBins.add(new Tbin<Aluminum>());
|
|
|
|
trashBins.add(new Tbin<Paper>());
|
|
|
|
trashBins.add(new Tbin<Glass>());
|
2015-05-05 11:20:13 -07:00
|
|
|
// add one line here: (*3*)
|
2015-05-18 23:05:20 -07:00
|
|
|
trashBins.add(new Tbin<Cardboard>());
|
2015-05-05 11:20:13 -07:00
|
|
|
|
|
|
|
trashBins.sortBin(bin); // (*4*)
|
|
|
|
|
2015-05-18 23:05:20 -07:00
|
|
|
Iterator<Tbin> e = trashBins.iterator();
|
|
|
|
while(e.hasNext())
|
|
|
|
Trash.sumValue(e.next());
|
2015-05-05 11:20:13 -07:00
|
|
|
Trash.sumValue(bin);
|
|
|
|
}
|
|
|
|
} ///:~
|