Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can an Integer be added to a String ArrayList?

Tags:

java

arraylist

List list = new ArrayList<String>() ;
list.add(1) ;
Integer hello = (Integer) list.get(0) ;
System.out.println(hello);

The above code has a reference of type List referring to an instance of ArrayList of type String. When the line list.add(1) is executed, isn't the 1 added to the ArrayList (of type String) ? If yes, then why is this allowed?

like image 545
Ace McCloud Avatar asked Apr 25 '13 14:04

Ace McCloud


1 Answers

You have used type erasure, which means you have ignored previously set generic checks. You can get away with this as this as generics are a compile time feature which isn't checked at runtime.

What you have the same as

List list = new ArrayList() ;
list.add(1) ;
Integer hello = (Integer) list.get(0) ;
System.out.println(hello);

or

List<Integer> list = new ArrayList<Integer>() ;
list.add(1) ;
Integer hello = list.get(0); // generics add an implicit cast here
System.out.println(hello);

If you look at the byte code generated by the compiler, there is no way to tell the difference.

Interestingly, you can do this

List<String> strings = new ArrayList<String>();
@SuppressWarnings("unchecked");
List<Integer> ints = (List) strings;
ints.add(1);

System.out.println(strings); // ok
String s= strings.get(0); // throws a ClassCastException
like image 88
Peter Lawrey Avatar answered Sep 20 '22 06:09

Peter Lawrey