简体   繁体   中英

Java explicit casting on list.get(0) (incompatible types: java.lang.Object cannot be converted to java.lang.String)

The following code is mentioned in the Java Tutorials:-( https://docs.oracle.com/javase/tutorial/java/generics/why.html )

List list = new ArrayList();
list.add("hello");
String s = (String) list.get(0);

The casting in the last line suggests that list.get(0) does not return a String. Now, since list was not declared with any data type, it can take in any object. So I assumed that list.get(0) returns an Object type.

But when I check list.get(0) instanceof String --> it returns true.

Why is then the explicit casting required. Please explain.

So I assumed that list.get(0) returns an Object type.

Yes it does.

But when I check list.get(0) instanceof String --> it returns true.

Yes, it should return true because the item at index 0 of the list is a String .

Why is then the explicit casting required.

it's required simply because the list contains Object s and not every Object from the list is guaranteed to be a String . The explicit cast is required so that you can assign the reference of list.get(0) to s (a variable of type String ).

The casting in the last line suggests that list.get(0) does not return a String.

That's inaccurate. If the returned object wasn't a String , then casting wouldn't have been possible. In other words, you can only cast something to String if that something is a String . Try casting something else, you'll see:

Object i = Integer.valueOf(5);
String j = (String)i; //Exception!

The cast is needed in your code because list.get(0) returns an Object type, but we want to assign it to a String s . We as the programmers know that the Object returned from the list is in fact a String , but the compiler doesn't. The compiler just sees this:

Object l = list.get(0);
String s = l;

The second line cannot compile without an explicit cast to String .

And just for clarification.. you'll never see such code in the real world unless you're working on something seriously old. Java has generics since Java 5 (2004), so 15 years now. At this point you really shouldn't see List without it being List<SomeType> (eg List<String> )

The List list = new ArrayList(); is an unparameterized type (which you want to avoid), meaning it can take any Object .

Since your list contains any Object s, list.get(0); can only know that it's returning an Object and doesn't know that the element at 0 is actually a String . Since it doesn't know that it's really a String the compiler warns you that you're doing an unchecked cast from Object to String .

list.get(0) instanceof String returns true because it's a runtime check that the element at 0 is in fact a String .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM