Re: Generics - What is the difference here ?
pramodr wrote:
Hi group,
While declaring a generic list, I can say
List<String> list = new ArrayList<String>();
However I fail to understand the difference between the above
declaration and
List<String> list = new ArrayList();
The compiler will issue an error message for the latter,
because it's trying to be helpful. Remember, the purpose of
generics is to catch type mismatch problems at compile time
instead of at run time; errors are usually less harmful if
they are caught and removed earlier.
Roughly speaking, the first line says
1) list is a List that holds String objects and
nothing else
2) the constructor call generates an ArrayList that
holds String objects and nothing else
3) list is initialized to refer to that ArrayList.
Since ArrayList implements List and since this
particular ArrayList holds only Strings, all
is well.
The second line says
A) list is a List that holds String objects and
nothing else
B) the constructor generates an ArrayList that can
hold any objects you like: Strings, Numbers,
JButtons, bool[] arrays, ...
C) list is initialized to refer to that ArrayList.
ArrayList implements List as before, but this one
isn't restricted containing Strings so the compiler
alerts you about the mismatch. The left-hand side
(list) has a requirement that the r.h.s. doesn't
satisfy.
I hope this helps.
--
Eric Sosman
esosman@ieee-dot-org.invalid