2

Suppose we're dealing with the following set up:

A extends B

Main does:

public void doIt() {
    List<A> listOfA = new ArrayList<A>();
    listOfA.add(new A());
    listOfA.add(new A());

    C c = new C();
    // We know that really, listOfA is going to be modified
    //  in some way and will be returned to us, thus, it is 
    //  ok to cast result back to what we know it to be
    List<A> a = (List<A>) c.doSomethingWithListOfA(listOfA);
}

When C has a method

public List<? extends B> doSomethingWithListOfA(List<? extends B> 
                                     listOfObjectsThatExtendB) {
    return someFormofListA;
}

The cast of (List) c.doSomethingWithListOfA(listOfA); comes back with - Type safety: Unchecked cast from List<capture#1-of ? extends B> to List<A> warning.

I wonder is it possibly because some other class may also extend B thus making compiler unsure whether in fact is it a list of A or possibly X that extends B?

Other then suppressing the warning, how can one check for this? (unchecked cast)

James Raitsev
  • 92,517
  • 154
  • 335
  • 470

1 Answers1

3

It's not type-safe because that method could return a list of any type which is a subtype of B -- which may or may no be A.

How about writing this:

public <T extends B> List<T> doSomethingWithListOfA(List<T> listOfObjectsThatExtendB) {
  return listOfObjectsThatExtendB;
}

and now casting is no longer needed:

List<A> a = c.doSomethingWithListOfA(listOfA);
JimN
  • 3,120
  • 22
  • 35