I am just a little curious about the difference between
List<String> list = new LinkedList<String>() and
List<String> list2 = new LinkedList();
It seems complier will check the type of objects added in both list and list2. Also Because Java complier use Type Erasure and there is no type information for objects inside both lists at run time. So they are the same?
Could anyone helps? Thanks in advance!
I don't know the canonical answer, but if you ever update your code and pass a parameter to the constructors, the generic one will do type checking but the non-generic one will not. For example:
List<Integer> intList = new LinkedList<Integer>();
List<String> list2 = new LinkedList(intList); // this is legal, senseless, but legal
List<String> list = new LinkedList<String>(intList); // this is not
En...It is very interesting, many thanks Fubarable!
The list2 initialization does cause a compiler warning (and rightly so). IMHO generics are a mixed blessing: I like the fact that it doesn't cause "code bloat" as it can do in C++ but I dislike the erasure thingy (which is a consequence of the design of it all). I also dislike the code backwards compatibility of allowing "raw" types which effectively annihilates even compile time checks.
Originally Posted by Fubarable