55 lines
1.4 KiB
Java
Raw Normal View History

2015-04-20 15:36:01 -07:00
//: generics/Fill.java
2015-05-29 14:18:51 -07:00
// <20>2015 MindView LLC: see Copyright.txt
2015-04-20 15:36:01 -07:00
// Generalizing the FilledList idea
// {main: FillTest}
import java.util.*;
// Doesn't work with "anything that has an add()." There is
// no "Addable" interface so we are narrowed to using a
// Collection. We cannot generalize using generics in
// this case.
public class Fill {
public static <T> void fill(Collection<T> collection,
Class<? extends T> classToken, int size) {
for(int i = 0; i < size; i++)
// Assumes default constructor:
try {
collection.add(classToken.newInstance());
2015-05-06 12:09:38 -07:00
} catch(InstantiationException |
IllegalAccessException e) {
2015-04-20 15:36:01 -07:00
throw new RuntimeException(e);
}
}
}
class Contract {
private static long counter = 0;
private final long id = counter++;
2015-05-05 11:20:13 -07:00
@Override
2015-04-20 15:36:01 -07:00
public String toString() {
return getClass().getName() + " " + id;
}
}
class TitleTransfer extends Contract {}
2015-05-18 23:05:20 -07:00
2015-04-20 15:36:01 -07:00
class FillTest {
public static void main(String[] args) {
2015-05-05 11:20:13 -07:00
List<Contract> contracts = new ArrayList<>();
2015-04-20 15:36:01 -07:00
Fill.fill(contracts, Contract.class, 3);
Fill.fill(contracts, TitleTransfer.class, 2);
for(Contract c: contracts)
System.out.println(c);
SimpleQueue<Contract> contractQueue =
2015-05-05 11:20:13 -07:00
new SimpleQueue<>();
2015-04-20 15:36:01 -07:00
// Won't work. fill() is not generic enough:
// Fill.fill(contractQueue, Contract.class, 3);
}
} /* Output:
Contract 0
Contract 1
Contract 2
TitleTransfer 3
TitleTransfer 4
*///:~