Search code examples
javanested-generics

Inconvertible types with nested generics


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.


Solution

  • 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);