-1

Return type of Arrays.asList is List and casting it to ArrayList is throwing an error. ArrayList is a child implementation class of List.So, Casting List to ArrayList will be downcasting. Then why below 1st line is throwing Run time error.

ArrayList<String> list  = (ArrayList<String>) Arrays.asList("Amit","Suneet","Puneet");// Run time Error
List<String> list2 = new ArrayList<>(list);

Error:

Exception in thread "main" java.lang.ClassCastException: java.util.Arrays$ArrayList cannot be cast to java.util.ArrayList

Can't we perform downcasting with interface and implementation class? If can then how?

4
  • 2
    Downcasting does not always succeed, you know. Commented Oct 14, 2020 at 0:18
  • I think this is an interesting question that deserves more consideration. The answer stackoverflow.com/a/64344883/348975 raises the obvious question why did the java implementers create two ArrayList implementations. java.util.Arrays.ArrayList (private) and java.util.ArrayList. Without reading the code, it seems pretty dumb to me. Commented Oct 14, 2020 at 0:47
  • @emory, that should be a separate question. The question as posted is pretty directly answered by the duplicate. Commented Oct 14, 2020 at 0:52
  • However, in general you should not be downcasting. That is a bad coding practice and should be avoided. Commented Oct 14, 2020 at 0:52

1 Answer 1

4

You can only downcast from Foo to SubFoo if the object actually being referenced is of type SubFoo. If the object is of type OtherSubFoo, you will get a ClassCastException.

That is the situation here. There is a class (private, as it should be) called java.util.Arrays.ArrayList, which is different from java.util.ArrayList. The object is of type java.util.Arrays.ArrayList, so it can't be cast to java.util.ArrayList. The same thing would happen, for example, if it were a LinkedList.

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.