Hi ranchers,
Some remarks about the differences between the posters in this
thread:
"A. The type List<A> is assignable to List."
means that type List can refer to a List<A>. So list = la, not the other way round. If you mix this up, you get errors.
And:
When we say (as I) e.g.
"List<A>
takes only A, no subtypes"
that means, that you can add only objects, that are of reference type A. But you can also add Subtypes to this list (B,C,D...).
What you can not do is refering to subtypes between the collections.
so
List<A> la = new ArrayList<A>();
List<B> lb = new ArrayList<B>();
A a = new A();
B b = new B();
la.add(a);// OK
la.add(b);// OK
la = lb;// wrong
B out = (B) la .get(1);
The last line is fine, but would not compile without the explicit cast, as you get only As out of the A list.
The question:
A. The type List<A> is assignable to List.
List<A> la = null;
List list = null;
list = la; <-- compiles without warning
This has to compile, otherwise you would not be able to use pre-Java 5 classes using collections.
No warning, because whatever is in la, it cannot harm a non-generic List.
The other way round
la = list; would also compile. But with a warning.
B. The type List<B> is assignable to List<A>.
List<A> la = null;
List<B> lb = null;
la = lb; <--- does not compile
That's why generic are used. To not let compile this.
C. The type List<Object> is assignable to List<?>.
List<Object> lo = null;
List<?> lu = null; // lu for list of unknown
lu = lo; <--- compiles without warning
A list of unknown can refer to any list.
The other way round would cause a compiler error.
D. The type List<D> is assignable to List<? extends B>.
List<D> ld = null;
List<? extends B> lb_lower = null;
lb_lower = ld; <--- compiles without warning
<? extends B> takes B type and children.
<B> would take only B.
E. The type List<? extends A> is assignable to List<A>.
List<A> la = null;
List<? extends A> la_lower = null;
la = la_lower; <--- does not compile
List<A> can only take type A, no other types and no subtypes of A.
F. The type List<Object> is assignable to any List reference
List<A> la = null; // la as example of any
List<Object> lo = null;
la = lo; <--- does not compile
List<X> takes only X, no subtypes. This is true for X=Object as well.
This wouldn't work in the other direction as well.
G. The type List<? extends B> is assignable to List<? extends A>.
List<? extends A> la_lower = null;
List<? extends B> lb_lower = null;
la_lower = lb_lower; <--- compiles without warning
<? extends B> is "smaller" than <? extends A> and so fits in.
Yours,
Bu.
[ December 19, 2006: Message edited by: Burkhard Hassel ]