Language specification: Why can't I assign list of string to list
of object?
Hi,
I'm interested in any reference to discussions, why the
language specification was made so that
"Subtyping does not extend through generic types: T <: U does not imply
that C<T> <: C<U>."
(JLS chapter 4.10)
As seen in this example:
$ cat G.java; javac -Xlint G.java
import java.util.List;
class G {
List<String> ls; List<Object> lo; List l; String s;
public void m() { lo.add(s); lo=ls; lo=(List<Object>)ls; l=ls; lo=l; }
}
G.java:4: incompatible types
found : java.util.List<java.lang.String>
required: java.util.List<java.lang.Object>
public void m() { lo.add(s); lo=ls; lo=(List<Object>)ls; l=ls; lo=l; }
^
G.java:4: inconvertible types
found : java.util.List<java.lang.String>
required: java.util.List<java.lang.Object>
public void m() { lo.add(s); lo=ls; lo=(List<Object>)ls; l=ls; lo=l; }
^
G.java:4: warning: [unchecked] unchecked conversion
found : java.util.List
required: java.util.List<java.lang.Object>
public void m() { lo.add(s); lo=ls; lo=(List<Object>)ls; l=ls; lo=l; }
^
2 errors
1 warning
it is no possible to assign the list of strings to the list of objects.
I find this behaviour quite annoying - even more so as the Java language
specification allows the workaround via the non-generic list "for the sake
of compatibility with older code" - that I wonder what kind of expected
problems led the designers of genericity in Java to disallow the direct
assignment of e.g. a list of string to a list of object.
If you can point me to any discussions about this on the web I would
appreciate it.
Thank you very much,
claudio
--
Claudio Nieder, Kanalweg 1, CH-8610 Uster, Tel +41 79 357 6743
yahoo messenger: claudionieder aim: claudionieder icq:42315212
mailto:private@claudio.ch http://www.claudio.ch