返回有界通配符

时间:2015-02-21 15:26:26

标签: java generics return

我有一个带有返回有界通配符的方法的接口:

public Collection<? extends CacheableObject> retrieveConnections(CacheableObject element);

此接口由类名PersistentAbstraction实现,返回CacheableObject

public Collection<? extends CacheableObject> retrieveConnections(CacheableObject element) {
    Collection<CacheableObject> connections = new HashSet<CacheableObject>();
    for(CacheableRelation relation : connectedElements) {
        if(relation.contains(element)) {
            connections.add(relation.getRelatedElement(element));
        }
    }
    return connections;
}

现在我有一个名为CacheableObject的{​​{1}}实现和一个User实例的类。我正在尝试执行以下操作:

PersistentAbstraction

但它说:

public Collection<User> retrieveConnections(User user) {
    Collection<User> collection = (Collection<User>) persistentAbstraction.retrieveConnections(user);
    return collection;
}

我不确定这个警告背后的原因是什么。用户不是CacheableObject吗?警告意味着什么?

2 个答案:

答案 0 :(得分:3)

错误基本上意味着您无法将Collection<? extends CacheableObject>分配给Collection<User>,因为无法保证在运行时集合对象的类型为User

Collection<? extends CacheableObject>引用可能会很好地指出一个集合,其中包含AnotherCacheableObject 实现 AnotherCacheableObject的{​​{1}}类型的项目。

答案 1 :(得分:1)

retrieveConnections返回Collection<? extends CacheableObject>。这可能是Collection<User>,但编译器无法知道这一点,因为它可能是Collection<OtherClass>,其中OtherClass是实现CacheableObject的其他类。

有几种方法可以解决这个问题。一种方法是使retrieveConnections成为带签名的通用方法

public <T extends CacheableObject> Collection<T> retrieveConnections(T element)

(您需要相应地修改方法的主体)。然后persistentAbstraction.retrieveConnections(user)将有Collection<User>类型,并且不需要演员。

相关问题