Tavo
Tavo

Reputation: 3151

Returning a bounded wildcard

I have an interface with a method that returns a bounded wildcard:

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

This interface is being implemented by a class name PersistentAbstraction that returns a 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;
}

And now I have an implementation of CacheableObject called User and a class that has an instance of PersistentAbstraction. I am trying to do the following:

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

But it says:

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

I am not sure what is the reason behind that warning. Isn't User a CacheableObject? What does the warning mean?

Upvotes: 0

Views: 143

Answers (2)

Paul Boddington
Paul Boddington

Reputation: 37655

retrieveConnections returns a Collection<? extends CacheableObject>. This could be a Collection<User> but there is no way for the compiler to know this as it could be a Collection<OtherClass> where OtherClass is some other class implementing CacheableObject.

There are several ways to fix this. One would be to make retrieveConnections a generic method with signature

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

(You will need to modify the body of the method accordingly). Then persistentAbstraction.retrieveConnections(user) will have type Collection<User> and there will be no need for the cast.

Upvotes: 1

Ravi K Thapliyal
Ravi K Thapliyal

Reputation: 51721

The error basically means that you cannot assign Collection<? extends CacheableObject> to Collection<User> and that's because there's no guarantee that at runtime the collection objects will be of type User.

A Collection<? extends CacheableObject> reference may very well point a collection holding items of type AnotherCacheableObject where AnotherCacheableObject implements CacheableObject.

Upvotes: 3

Related Questions