15.4.3 用于Generator的泛型方法
利用生成器,可以方便的填充一個(gè)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 一個(gè)通用的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());
}
}
練習(xí)14:
總結(jié)
以上是生活随笔為你收集整理的15.4.3 用于Generator的泛型方法的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 15.4.2:可变参数与泛型化方法
- 下一篇: 15.4.5 简化元组的使用