利用生成器,可以方便的填充一个Collection,而泛型化
pubilc class Generators{
public static<T> Collection<T> fill(Collection<T> coll,Generator<T> gen,int n){
for(int i=0;i<n;i+)
coll.add(gen.next());
return coll;
}
}
15.4.4 一个通用的Generator
pubic class BasicGenerator<T> implements Generator<T>{
private class<T> type;
public BasicGenerator(Class<T> type){this.type=type;)}
public T next(){
try{
return type.newIntance();
}catch(Exception e){
throw new RuntimException(e);}
public static<T> Generation<T> create(Class<T> type){
return new BasicGenerator<T>(type);
}
如:public class CountedObject{
private static long counter=0;
private final long id=counter++;
public long id(){return id;}
public String toString(){return "CounterObject"+id:}
}
main(){
Generator<CountedObject> gen=BasicGenerator.create(CountedObject.class);
for(int i=0;i<5;i++)
sysout(gen.next());
}
}
练习14: