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.

2
  • 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. Commented Jul 20, 2018 at 16:49
  • new ArrayList() can be seen as new ArrayList<Object>() Commented Jul 20, 2018 at 16:52

1 Answer 1

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."

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.