Re: Casting between typed Lists?
<jagonzal@gmail.com> wrote in message
news:1155935651.255703.25460@p79g2000cwp.googlegroups.com...
Hi,
I have an Interface B, which extends Interface A.
I have a method whose signature is:
public void doSomething(List<A> list){
...
}
However, when I try to invoke it like this:
List<B> list2 = new ArrayList<B>();
doSomething(list2);
the compiler complains that it can't take a List<B> instead of a
List<A>. I say that, theoretically, it should work, since a B element
is also a A element due to interface inheritance. Casting a B variable
to A does not produce a ClassCastException. However, the compiler says
that it doesn't.
Is there any way to go around this (Other than working with non-typed
lists)? (casting the list? I tried that but it doesn't work :)
Instead of "A" and "B", let's call them "Vehicule" and "Car". Car
extends Vehicule.
The doSomething(List<Vehicule> list) method does something to a list of
vehicules. One of the things it might do is add more vehicules to the list.
For example, it might add some boats to the list.
If you pass in a List<Car> instead of a List<Vehicule>, you'll get an
problems, because the doSomething method will try to add a Boat to a
List<Car>, and obvious a Boat is not a Car.
Solution A: change the method signature from doSomething(List<A> list)
to doSomething(List<? extends A> list).
Solution B: change the object declaration from List<B> list2 = new
ArrayList<B>() to List<A> list2 = new ArrayList<A>().
Which solution is better depends entirely on what it is your program is
supposed to do.
- Oliver