2

What is difference in following two declarations

List<Integer> l = new ArrayList(); //and 

List<Integer> l = new ArrayList<Integer>();

If not then why in java 7 dimond operator ie <> is introduced to avoid type writing at right side of '=' or at object creation side.

Prashant Shilimkar
  • 8,402
  • 13
  • 54
  • 89

2 Answers2

4

Consider this example

List<Float> f = new ArrayList();     // this list hold(s) Float(s).
f.add(2.0f);
List<Integer> l = new ArrayList(f);  // Oh no.... 
l.add(1);
System.out.println(l);            

If I run the above I get

[2.0, 1]

If I used the diamond operator, I would get a compiler error. Does that help? At run-time every Collection holds java.lang.Ojbect(s) due to type erasure, this is compile time type checking only.

Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
2

This will causes the [unchecked] warning:

List<Integer> l = new ArrayList(); 

refer here

Community
  • 1
  • 1
Nambi
  • 11,944
  • 3
  • 37
  • 49