Re: A problem regarding generics
On 06/06/2010 07:02 AM, Vikram wrote:
In java generics, the following code gives compile time error.
List<Object> list = new ArrayList<String>(); // compile time error
Step back and think for a moment. Since we have a list of Strings, we
need to forbid adding a generic Object to the list. Allowing you to cast
List<String> to List<Object> would permit a list.add(new Object()),
which is clearly not what we want to allow .
What we want then is a list of things whose type we don't know--but we
can guarantee them to be at least of type Object. The proper type for
this is the wildcard List<? extends Object>; the typing rules would then
allow you to observe a list.getFirst() as returning Object but prohibit
you from adding a plain old Object to that list.
Where as the following does not give any compile time error
List list = new ArrayList<String>();
It doesn't give an error, but it does give you the unchecked conversion
for using a raw type.
If no generics is specified, isin't it implied that it contains
object? What is the reason the second statement does not give any
compile time error?
Actually, a raw type is roughly equivalent to List<?> ; List<?> is
equivalent to List<? extends Object>.
 The reason that the array analogue allows you to do Object o = new
String; is because the type of the array is stored, so actually
saying o = new Object(); will fail at runtime with an
ArrayStoreException. The generic types are not reified in Java , so
the compiler can't do the same guarantee at runtime that arrays do.
 A main point of distinction: List.class is of type Class<List>, not
Class<List<?>>, and you can't really convert between the two. Even the
Java developers admit this is a mistake, but they won't fix it since
doing so would break existing code. This has caused me a great deal of
 Well, Collections.checkedList (et al.) do actually let you achieve
the same runtime storage checking, and it is always possible to make
your own wrappers for types you create. But it's not given to your for
free by the language, owing mostly to the desire to gain
backwards/forwards compatibility and partial library migration.
Beware of bugs in the above code; I have only proved it correct, not
tried it. -- Donald E. Knuth