Java泛型 - 如何将非泛型添加到通用列表

时间:2016-06-18 03:16:16

标签: java generics

我尝试创建一个方法,将定义列表中的元素添加到通用列表中。

以下是代码:

private List<IEntity> entities = new ArrayList<IEntity>();

public <T extends IEntity> List<T> values(Class<T> type) {
    List<T> types = new ArrayList<T>();

    for (IEntity v : entities) {
        types.add(v); //Error
    }

    return types;
}

types.add(v);上发生sytax错误,错误消息为(T) in List cannot be applied to (com.test.entities.IEntity)

有没有什么方法可以做我想要有效地做而无需演员的事情?

4 个答案:

答案 0 :(得分:9)

编译器为您提供类型错误,因为您的程序不安全。

你有List<T>。你不知道T是什么,只是它延伸IEntity。 (让我们使用数字作为示例,而不是IEntity,以使其更清晰。)所以你有一个某种数字的列表,也许它是List<Integer>,或者也许是List<Float>,你不知道。而你正在尝试为其添加一个数字。但你没有理由相信这个名单可以容纳数字! List<Integer>不能保存任意数字,因为您不能将Long或Float或Short放入List<Integer> - Java泛型是不变的。

所以,基本上你的程序坏了,编译器告诉你了。

答案 1 :(得分:0)

您无法将IEntity插入包含IEntity - T extends IEntity子类的列表。您需要一个包含超级IEntity类的列表,以便在其中添加IEntity - T super IEntity

答案 2 :(得分:0)

由于您没有提供有关您将要做的具体结构的更多信息,因此很难提供更好的解决方案。

interface Entity {} // In Java, unlike in .NET environment, interface names do not begin with "I". You write Entity or EntityInterface, sometimes also EntityInt

class EntityImpl {
    private final List<Entity> entities = new ArrayList<>();

    // List of T is undefined
    public <T extends Entity> List<T> getValues(Class<T> type) { // in Java it's important to write "get" for a getter-method before the property-name, if it's not a boolean-getter.
        List<T> types = new ArrayList<>();
        types.addAll((Collection<? extends T>) entities);
        return types;
    }
}

答案 3 :(得分:0)

如果你想制作一个通用类,你可以做这样的事情。

private class MyClass<T extends IEntity> {
    private List<T> entities;

    ...

    public List<T> values() {
        List<T> types = new ArrayList<>();

        for (T v : entities) {
            types.add(v); // All Good
        }
        return types;
    }
} 

interface IEntity { ... }

interface ISubEntity extends {...}

然后,当您知道您正在使用ISubEntity时,您可以实例化如下;

MyClass<ISubEntity> myClass = new MyClass<>(); 

随后对值的调用将返回为您键入的List。

这是关于泛型的正式doc在线。

相关问题