JAVA错误:无法将Ljava.lang.Object;强制转换为[Ljava.util.ArrayList;。

huangapple 未分类评论49阅读模式
英文:

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&lt;Integer&gt;[] arr = (ArrayList&lt;Integer&gt;[]) new Object[2];
    	}
    }

&gt; Runtime Errors: Exception in thread &quot;main&quot;
&gt; java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to
&gt; [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&lt;&gt;();
if (o instanceof ArrayList) {
    ArrayList&lt;String&gt; arr = (ArrayList&lt;String&gt;) o;
}

huangapple
  • 本文由 发表于 2020年4月7日 12:10:29
  • 转载请务必保留本文链接:https://java.coder-hub.com/61072702.html
匿名

发表评论

匿名网友

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

确定