> Hi,
>
[quoted text clipped - 19 lines]
> 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
jagonzal@gmail.com - 18 Aug 2006 22:47 GMT
> 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.
[quoted text clipped - 3 lines]
> problems, because the doSomething method will try to add a Boat to a
> List<Car>, and obvious a Boat is not a Car.
Ah, I had not considered this scenario - thank you :)
> Solution A: change the method signature from doSomething(List<A> list)
> to doSomething(List<? extends A> list).
I think I'll go with this - I'm getting the list from another object,
and I can't change that return type.
> Which solution is better depends entirely on what it is your program is
> supposed to do.
>
> - Oliver
Thank you very much :)