返回有界通配符

Returning a bounded wildcard

我有一个接口,其方法 returns 有界通配符:

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

此接口由 class 名称 PersistentAbstraction 实现,returns 名称 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;
}

现在我有一个名为 UserCacheableObject 实现和一个具有 PersistentAbstraction 实例的 class。我正在尝试执行以下操作:

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

但是它说:

Type safety: Unchecked cast from Collection<capture#1-of ? extends CacheableObject> to Collection<User>

我不确定该警告背后的原因是什么。 User 不是 CacheableObject 吗?警告是什么意思?

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

一个 Collection<? extends CacheableObject> 引用很可能指向一个包含 AnotherCacheableObject 类型项目的集合,其中 AnotherCacheableObject 实现 CacheableObject

retrieveConnectionsreturns一个Collection<? extends CacheableObject>。这可能是一个 Collection<User>,但编译器无法知道这一点,因为它可能是一个 Collection<OtherClass>,其中 OtherClass 是其他一些 class 实现 CacheableObject .

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

的通用方法
public <T extends CacheableObject> Collection<T> retrieveConnections(T element)

(您需要相应地修改方法体)。然后 persistentAbstraction.retrieveConnections(user) 将具有类型 Collection<User> 并且不需要强制转换。