3

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.

Ronald
  • 343
  • 3
  • 10
  • I'd recommend researching static vs. dynamic typing and strong vs. weak typing, if you aren't familiar with those terms. Java has strong static typing which is why casts and generics like this are necessary, because what we're allowed to do with an object at some particular point in the program depends on its compile-time type. – Radiodef Jul 20 '18 at 16:49
  • `new ArrayList()` can be seen as `new ArrayList()` – Gabriel Jul 20 '18 at 16:52

1 Answers1

8

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 Objects, but trust me, the thing I'm pulling out is definitely a String."

John Kugelman
  • 349,597
  • 67
  • 533
  • 578