In thinking in Java, page 566 gives the following example.
class CountedInteger {
private static long counter;
private final long id = counter++;
public String toString() { return Long.toString(id); }
}
public class FilledList<T> {
private Class<T> type;
public FilledList(Class<T> type) { this.type = type; }
public List<T> create(int nElements) {
List<T> result = new ArrayList<T>();
try {
for(int i = 0; i < nElements; i++)
result.add(type.newInstance());
} catch(Exception e) {
throw new RuntimeException(e);
}
return result;
}
public static void main(String[] args) {
FilledList<CountedInteger> fl = new FilledList<CountedInteger>(CountedInteger.class);
System.out.println(fl.create(15));
}
}
I have three questions with respect to this example.
1) What is the usage of private Class type? Why is it private?
2) Why do the following, in particular ” this.type = type;”
public FilledList(Class<T> type) { this.type = type; }
3) The author claims:
Notice that this class must assume that any type that it works with
has a default constructor (one without arguments), and you’ll get an
exception if that isn’t the case.
I can not figure out how this statement was reflected in the above example. Thanks.
1) It doesn’t have to be, but that’s one of the things you do in Java–don’t expose things that don’t need to be exposed.
2) That sets the property to the parameter of the constructor–that’s elemental Java.
3) Because of the
type.newInstance()call; without a default (no-arg) constructor it will fail.