I'm learning about generics and I have a misunderstanding.
For example I have this simple code:
import java.util.ArrayList;
public class DemoApp {
public static void main(String[] args) {
ArrayList list = new ArrayList();
list.add(1);
System.out.println(list.get(0).getClass().getName());
int value = (Integer) list.get(0);
}
}
I don't understand why should I cast the list.get(0)
to Integer
because this statement System.out.println(list.get(0).getClass().getName());
has this result java.lang.Integer
?
If I use this statement int value = list.get(0);
I get this error: Type mismatch: cannot convert from Object to int
... and I really don't understand, is list.get(0)
an Object
or an Integer
?