为什么无法将Arrays.asList()的结果转换为ArrayList?

huangapple go评论66阅读模式
英文:

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&lt;String&gt; list  = (ArrayList&lt;String&gt;) Arrays.asList(&quot;Amit&quot;,&quot;Suneet&quot;,&quot;Puneet&quot;);// Run time Error
List&lt;String&gt; list2 = new ArrayList&lt;&gt;(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.

huangapple
  • 本文由 发表于 2020年10月14日 08:15:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/64344844.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定