Friday 23 May 2008

Java generics - assigning a List<C> where type D implements interface D to a variable of List<D> - can't be done - AKA:Type Erasure ARRGH!

Java generics still confuse me.

A work colleague was asking me something about assigning typed lists
and it wasn't working the way
it would work if you were simply dealing with single variables.

Class C implements interface D.

Then we have a list of interface D.

Another class E has a method findAll() which returns a list of type C.

But we can't assign E.findAll() to a list of type D.


List<Comparable> listOne;

listOne.add("String");
listOne.add(new Long(1000));

BUT

listTwo = new ArrayList<Long>();

listTwo.add(new Long(33));

listOne = listTwo;

Error: "Incompatible types, Required List<java.lang.Comparable> Found:
List<java.util.List>"


Hmm... maybe we can cast the list?

listOne = (List<Comparable>) listTwo;

Error: Inconvertible types; cannot cast
'java.util.List<java.lang.Long>' to
'java.util.List<java.lang.Comparable>'

But why?

No comments: