-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?

user207421
  • 305,947
  • 44
  • 307
  • 483
  • 2
    Downcasting does not always succeed, you know. – Sweeper Oct 14 '20 at 00:18
  • I think this is an interesting question that deserves more consideration. The answer https://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. – emory Oct 14 '20 at 00:47
  • @emory, that should be a separate question. The question as posted is pretty directly answered by the duplicate. – Louis Wasserman Oct 14 '20 at 00:52
  • However, in general you should not be downcasting. That is a bad coding practice and should be avoided. – emory Oct 14 '20 at 00:52

1 Answers1

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.

Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413