It's compiles and run successfully!
List a=new ArrayList<String>();
a.add(new Integer(5));
Can anybody explain this?
Reason is that you are declaring variable a to be a raw list i.e. List without any associated type:
List a = new ArrayList<String>();
For that matter even this will compile & run:
List a = new ArrayList<Date>();
a.add(new Integer(5));
Also a note about generics and type erasure here:
Generics are implemented by Java compiler as a front-end conversion called erasure. Type erasure applies to the use of generics. When generics are used, they're converted into compile time checks and run time type casts.
Due to type erasure mechanism this code:
List<String> a = new ArrayList<String>();
a.add("foo");
String x = a.get(0);
gets compiled into:
List a = new ArrayList();
a.add("foo");
String x = (String) a.get(0);
Similarly your code:
List a = new ArrayList<String>();
a.add(new Integer(5));
gets compiled into this (due to type erasure):
List a = new ArrayList();
a.add(new Integer(5));
Thus no compilation or run time error is generated.
However you will note the difference when you try to do get item from the list:
int i = a.get(0); // compilation error due to type mismatch
Which is due to the fact that your list is declared as raw type. To avoid this error you need to either use generics to declare your list OR else do a type cast like above. i.e.
Either use generic type in your list:
List<Integer> a = new ArrayList<Integer>();
a.add(new Integer(5));
int i = a.get(0);
Or else do this casting: (not recommended)
List a=new ArrayList<Date>();
a.add(new Integer(5));
int i = (Integer) a.get(0);
PS: Note that at run time there's no way of finding out that particular type e.g. String was used for declaring your list object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With