85 lines
2.5 KiB
Java
Raw Normal View History

2015-11-03 12:00:44 -08:00
// patterns/recyclec/RecycleC.java
2016-12-30 17:23:13 -08:00
// (c)2017 MindView LLC: see Copyright.txt
2015-11-15 15:51:35 -08:00
// We make no guarantees that this code is fit for any purpose.
2016-09-23 13:23:35 -06:00
// Visit http://OnJava8.com for more book information.
2016-01-25 18:05:55 -08:00
// Adding more objects to the recycling problem
2016-07-28 12:48:23 -06:00
// {java patterns.recyclec.RecycleC}
2015-11-03 12:00:44 -08:00
package patterns.recyclec;
import patterns.trash.*;
import java.util.*;
// 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;
}
@SuppressWarnings("unchecked")
boolean grab(Trash t) {
// Comparing class types:
if(t.getClass().equals(binType)) {
add((T)t); // Downcast to this TBin's type
return true; // Object grabbed
}
return false; // Object not grabbed
}
}
class TbinList<T extends Trash>
2017-01-20 21:30:44 -08:00
extends ArrayList<Tbin<? extends T>> { // [1]
2015-11-03 12:00:44 -08:00
boolean sort(T t) {
for(Tbin<? extends T> ts : this)
if(ts.grab(t))
return true;
return false; // bin not found for t
}
2017-01-20 21:30:44 -08:00
void sortBin(Tbin<T> bin) { // [2]
2015-11-03 12:00:44 -08:00
for(T aBin : bin)
if(!sort(aBin))
System.err.println("Bin not found");
}
}
public class RecycleC {
static Tbin<Trash> bin = new Tbin<>(Trash.class);
public static void main(String[] args) {
// Fill up the Trash bin:
ParseTrash.fillBin("trash", bin);
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));
2017-01-20 21:30:44 -08:00
trashBins.sortBin(bin); // [4]
2015-11-03 12:00:44 -08:00
trashBins.forEach(Trash::sumValue);
Trash.sumValue(bin);
}
}
2016-07-20 06:32:39 -06:00
/* Output: (First and Last 10 Lines)
2015-11-03 12:00:44 -08:00
Loading patterns.trash.Glass
Loading patterns.trash.Paper
Loading patterns.trash.Aluminum
Loading patterns.trash.Cardboard
weight of patterns.trash.Aluminum = 89.0
weight of patterns.trash.Aluminum = 76.0
weight of patterns.trash.Aluminum = 25.0
weight of patterns.trash.Aluminum = 34.0
weight of patterns.trash.Aluminum = 27.0
weight of patterns.trash.Aluminum = 18.0
2016-07-22 14:45:35 -06:00
...________...________...________...________...
2015-11-03 12:00:44 -08:00
weight of patterns.trash.Aluminum = 93.0
weight of patterns.trash.Glass = 93.0
weight of patterns.trash.Paper = 80.0
weight of patterns.trash.Glass = 36.0
weight of patterns.trash.Glass = 12.0
weight of patterns.trash.Glass = 60.0
weight of patterns.trash.Paper = 66.0
weight of patterns.trash.Aluminum = 36.0
weight of patterns.trash.Cardboard = 22.0
Total value = 1086.0599818825722
*/