Click here to Skip to main content
15,891,850 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
What is the difference between
JavaScript
List<String> l=new ArrayList<String>()
and
Java
List<String> l=new ArrayList();

Can help anyone help and what is the principle?

Thanks!
Posted
Updated 19-Feb-12 1:41am
v3
Comments
André Kraak 19-Feb-12 7:11am    
Edited question:
Added pre tags
"Treat my content as plain text..." option disabled.

1 solution

That's pretty much the same as long as the Generic on the left side is set with a type.

But it can lead to strange situations when you do not set the type of the left sided value: value:
Java
List l = new ArrayList<string>();
List<Object> o = l;


That certainly works while adding things to the List, because String is an Object.

Java
o.add(new Object());
o.add("String");


But when you're fetching the values, it can lead to misbehavior:
Java
System.out.println(o.get(0)); // Exception because value(0) is no String.
 
Share this answer
 
v3
Comments
jessie345 20-Feb-12 6:05am    
but,I have always been confused,can you help me analyse the deeper principle.Thanks!
Also the: List<string> l=new ArrayList();,List l=new ArrayList<string>();,their behavior
were different,why?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900