Re: A problem regarding generics
On 6/6/2010 4:02 AM, Vikram wrote:
Hi,
In java generics, the following code gives compile time error.
List<Object> list = new ArrayList<String>(); // compile time error
Where as the following does not give any compile time error
List list = new ArrayList<String>();
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?
List<? extends Object> list = new ArrayList<String>(); // compiles fine
The difference between all three:
List<Object> list = new ArrayList<String>();
This says "A reference to List which can have any type of Objects added
and retrieved is assigned a List which can only have Strings added and
retrieved "
List list = new ArrayList<String>();
This says "A reference to a List which is of a Raw type, is assigned a
List which can only have Strings added and retrieved. "
The raw type remains as a backward compatibility in Java, and should not
be used in new code if possible.
List<? extends Object> list = new ArrayList<String>();
This says "A reference to a List which can have any Object retrieved,
but only objects of an unknown type can be added, is assigned a List
which can only have Strings added and retrieved. "
--
Daniel Pitts' Tech Blog: <http://virtualinfinity.net/wordpress/>