Inconvertible types with nested generics

538 Views Asked by At

I looked at the other typecasting Java generics questions I'm still confused.

I have the following class hierarchy: WeightedThing<T> (just adds a weight to some random type) and a custom Vector class of which WeightedVector (no, WeightedVector is not just WeightedThing<Vector>) is a subclass.

I want to do nearest neighbor search and return a list of the closest vectors to a given query vector and their distances. For this, I defined a search method:

public List<WeightedThing<? extends Vector>> search(Vector, int limit) {...}

hoping I can do

List<WeightedThing<WeightedVector>> neighbors = (List<WeightedThing<WeightedVector>>)search(query, 1);

That doesn't work (IntelliJ doesn't mark it as an error, but compiling it with Sun's jdk7u10 for Mac OS X fails). Neither does calling the same function with Vector. I can force it to compile by adding an upcast to Object, but that seems horrible.

The purpose of this is so I can search and add vectors of any type but if I know I only added WeightedVectors, I want to cast the results back to WeightedVectors.

2

There are 2 best solutions below

1
Amit Deshpande On BEST ANSWER

List of WeightedThing<? extends Vector> is not same as List of WeightedThing<WeightedVector>. To typecast it cast to wild char types that is any collection and then cast to specific type.

 List<WeightedThing<WeightedVector>> neighbors = (List<WeightedThing<WeightedVector>>)
                                                (List<?>)search(query, 1);
1
Ale E On

In general it is not a good practice to use wild char types in the return type of a method. Why don't you try to change the method signature as the following:

public <T extends Vector> List<WeightedThing<T>> search(T vector, int limit) {...}