英文:
Why it is not possible to cast the result of Arrays.asList() to ArrayList?
问题
The 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 is the first line below throwing a runtime 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 an interface and its implementation class? If we can, then how?
英文:
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?
答案1
得分: 4
你只能在实际引用的对象类型为 SubFoo
时,将 Foo
下转为 SubFoo
。如果对象的类型是 OtherSubFoo
,将会得到 ClassCastException
。
这就是目前的情况。有一个名为 java.util.Arrays.ArrayList
的类(按照应有的方式为私有类),它与 java.util.ArrayList
不同。对象的类型是 java.util.Arrays.ArrayList
,因此无法将其强制转换为 java.util.ArrayList
。例如,如果它是一个 LinkedList
,也会发生相同的情况。
英文:
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
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论