英文:
JAVA ERROR: Ljava.lang.Object; cannot be cast to [Ljava.util.ArrayList;
问题
以下是翻译好的部分:
请问有人能解释一下为什么我在下面的代码中出现了运行时错误吗?
(无需提供解决方案)谢谢!
import java.util.*;
class GFG {
public static void main (String[] args) {
ArrayList<Integer>[] arr = (ArrayList<Integer>[]) new Object[2];
}
}
运行时错误:线程“main”中的异常
java.lang.ClassCastException:无法将[Ljava.lang.Object; 强制转换为
[Ljava.util.ArrayList; at GFG.main(File.java:5)
<details>
<summary>英文:</summary>
Can anyone help to explain why I got this runtime error for the code below?
(no solution is needed) Thanks!
import java.util.*;
class GFG {
public static void main (String[] args) {
ArrayList<Integer>[] arr = (ArrayList<Integer>[]) new Object[2];
}
}
> Runtime Errors: Exception in thread "main"
> java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to
> [Ljava.util.ArrayList; at GFG.main(File.java:5)
</details>
# 答案1
**得分**: 0
来自`[ClassCastException][1]`的API规范的内容如下:
> 抛出以指示代码已尝试将对象转换为其不是实例的子类。
在您的情况下,您正在进行向下转型(将`Object`转型为`ArrayList`)。每个`ArrayList`都是一个`Object`,但并非每个`Object`都是`ArrayList`。
通常情况下,向下转型不是一个好主意。您应该尽量避免它。如果必须使用它,最好在使用`instanceof`进行检查。
```java
Object o = new ArrayList<>();
if (o instanceof ArrayList) {
ArrayList<String> arr = (ArrayList<String>) o;
}
英文:
Straight from the API Specifications for the [ClassCastException][1]
:
> Thrown to indicate that the code has
> attempted to cast an object to a
> subclass of which it is not an
> instance.
In your case, you are down-casting (casting Object
to ArrayList
). Every ArrayList
is an Object
, but not every Object
is an ArrayList
.
Generally, downcasting is not a good idea. You should avoid it. If you use it, you better include a check using instanceof
.
Object o = new ArrayList<>();
if (o instanceof ArrayList) {
ArrayList<String> arr = (ArrayList<String>) o;
}
专注分享java语言的经验与见解,让所有开发者获益!
评论