用于Generators的泛型方法
利用生成器,我们可以很方便地填充一个Collections
,而泛型化操作在这里是具有意义的。
public 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;
}
public static void main(String[] args) {
Collection<Coffee> coffees = fill(new ArrayList<>(), new CoffeeGenerator(), 4);
for (Coffee coffee : coffees) {
System.out.println("coffee = " + coffee);
}
Collection<Integer> fnumbers = fill(new ArrayList<>(), new Fibonacci(), 12);
for (int i : fnumbers) {
System.out.print(i + " ");
}
}
}
// Outputs
coffee = Americano 0
coffee = Latte 1
coffee = Americano 2
coffee = Mocha 3
1 1 2 3 5 8 13 21 34 55 89 144
这里的fill()
方法是一个泛型的方法,通过接收一个泛型的容器和一个泛型的生成器,通过调用next()
方法填充一个Collection
类型。
一个通用的Generator
public class BasicGenerator<T> implements Generator<T> {
private Class<T> type;
public BasicGenerator(Class<T> type) {
this.type = type;
}
@Override
public T next() {
try {
return type.newInstance();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static <T> Generator<T> create(Class<T> type) {
return new BasicGenerator<T>(type);
}
}
// Outputs
coffee = Americano 0
coffee = Latte 1
coffee = Americano 2
coffee = Mocha 3
1 1 2 3 5 8 13 21 34 55 89 144
这个类提供了一个基本实现,用来生成某个类的对象。
而这个类必须有一个public
权限的无参构造器,public
是因为BasicGenerator
和要处理的程序往往不在同一个包中,所以并不只是有packet
权限。
要创建BasicGenerator
对象,只需要调用create()
方法,并传入想要生成的类型。泛型化的方法create
方法通过返回new BasicGenerator<T>(type)
简化了生成。
使用
以下是一个具有默认生成器的简单类
public class CountedObject {
private static long counter = 0;
private final long id = counter++;
public long getId() {
return id;
}
@Override
public String toString() {
return "CountedObject " + id;
}
}
CountedObject
类能够记录下它创建了多少个CountedObject
实例,并通过toString()
方法打印出其编号。
使用BasicGenerator
,可以很容易地在CountedObject
创建一个Generator
。
public class BasicGeneratorDemo {
public static void main(String[] args) {
Generator<CountedObject> gen = BasicGenerator.create(CountedObject.class);
for (int i = 0; i < 5; i++) {
System.out.println("gen.next() = " + gen.next());
}
}
}
// Outputs
gen.next() = CountedObject 0
gen.next() = CountedObject 1
gen.next() = CountedObject 2
gen.next() = CountedObject 3
gen.next() = CountedObject 4
可以看到,使用泛型方法来创建Generator
对象,可以大大减少了我们要编写的代码。而其中,Java泛型要求传入Class
对象,以便也可以在onCreate()
方法中用它创建类型推断。