Reputation: 343
I'm trying to understand ArrayLists and in the process have realized I also need to understand generics, raw types, and more about type casting. I'm reading the Oracle tutorial and this is the example they give for why generics are helpful:
The following code snippet without generics requires casting:
List list = new ArrayList();
list.add("hello");
String s = (String) list.get(0);
What I don't understand is why type casting is necessary here because as far as I can tell 'list.get(0)' is of type 'String' before and after the typecasting. I used the code here to check the type, not sure if it's correct or not.
List list = new ArrayList();
list.add("hello");
Object obj= list.get(0);
Class cls=obj.getClass();
String answer = cls.getSimpleName();
System.out.println(answer);
String s = (String) list.get(0);
Object obj2= list.get(0);
Class cls2=obj2.getClass();
System.out.println(cls2);
String answer2 = cls2.getSimpleName();
System.out.println(answer2);
So I'm asking for an explanation as to why type casting is necessary here and in here non generic-ed Arraylists in general.
Upvotes: 3
Views: 106
Reputation: 361645
The run-time type is String
, but the compile-time type is Object
. The compiler doesn't know what a raw ArrayList
holds, so when you call get()
it assigns a compile-time type of Object
. An Object
can't be assigned directly to a String
, thus the cast.
The cast is the developer's way of saying to the compiler, "You think it's a list of Object
s, but trust me, the thing I'm pulling out is definitely a String
."
Upvotes: 8