// generics/Generators13.java // TIJ4 Chapter Generics, Exercise 13, page 637 /* Overload the fill() method so that the arguments and return types are * the specific subtypes of Collection: List, Queue and Set. This way, you * don't lose the type of container. Can you overload to distinguish between * List and LinkedList? */ import generics.coffee.*; import java.util.*; import net.mindview.util.*; import static org.greggordon.tools.Print.*; public class Generators13 { public static Collection fill(Collection coll, Generator gen, int n) { for(int i = 0; i < n; i++) coll.add(gen.next()); return coll; } public static List fill(List l, Generator gen, int n) { for(int i = 0; i < n; i++) l.add(gen.next()); return l; } public static Queue fill(Queue q, Generator gen, int n) { for(int i = 0; i < n; i++) q.add(gen.next()); return q; } public static Set fill(Set s, Generator gen, int n) { for(int i = 0; i < n; i++) s.add(gen.next()); return s; } // return type LinkedList: public static LinkedList fill(LinkedList ll, Generator gen, int n) { for(int i = 0; i < n; i++) ll.add(gen.next()); return ll; } public static void main(String[] args) { Collection coffee = fill(new ArrayList(), new CoffeeGenerator(), 4); for(Coffee c : coffee) System.out.println(c); Collection fnumbers = fill(new ArrayList(), new Fibonacci(), 12); for(int i : fnumbers) System.out.print(i + ", "); println(); List coffeeList = fill(new ArrayList(), new CoffeeGenerator(), 5); println("List type: " + coffeeList.getClass()); println("coffeeList:" + coffeeList); Queue coffeeQueue = fill(new ArrayDeque(), new CoffeeGenerator(), 5); println("Queue type: " + coffeeQueue.getClass()); println("coffeeQueue: " + coffeeQueue); Set coffeeSet = fill(new HashSet(), new CoffeeGenerator(), 5); println("Set type: " + coffeeSet.getClass()); println("coffeeSet: " + coffeeSet); LinkedList coffeeLinkedList = fill(new LinkedList(), new CoffeeGenerator(), 5); println("LinkedList type: " + coffeeLinkedList.getClass()); println("coffeeLinkedList: " + coffeeLinkedList); } }