在Java中将参数化类型用作通用类型

时间:2018-10-10 12:41:42

标签: java generics

关于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。有什么想法吗?

谢谢!

0 个答案:

没有答案