我有一个接口(interface),其方法返回有界通配符:
public Collection<? extends CacheableObject> retrieveConnections(CacheableObject element);
此接口(interface)由返回 CacheableObject
的类名 PersistentAbstraction
实现:
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;
}
现在我有一个名为 User
的 CacheableObject
实现,以及一个具有 PersistentAbstraction
实例的类。我正在尝试执行以下操作:
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
.
关于java - 返回有界通配符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28647460/