关于Java Genrerics,我有一个简短的问题:
有什么方法可以控制类型参数的泛型类型吗?难以解释的简短示例:;-)
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
public class GenericContainer<C extends Collection<T>, T> {
C collection;
public GenericContainer(C collection) {
this.collection = collection;
}
// I need both: the type of the collection's elements...
public boolean add(T t) {
return collection.add(t);
}
// ... and the type of the collection.
public C getCollection() {
return this.collection;
}
public static void main(String[] args) {
// Here it comes:
// Is it possible to remove the redundant "String" in the generic declaration?
GenericContainer<List<String>, String> container = new GenericContainer<>(Arrays.asList("Foo", "Bar"));
}
}
因此,如评论中所述,我的目标是拥有一个更简单的版本:
用冗余字符串替换GenericContainer<List<String>> container
而不是GenericContainer<List<String>, String> container
。有什么想法吗?
谢谢!