java - 为什么 ArrayStoreException 是 RuntimeException?

标签 java arrays exception exception-handling runtimeexception

假设我们有以下程序:

class Fruit {}

class Apple extends Fruit {} 

class Jonathan extends Apple {} 

class Orange extends Fruit {} 

public class Main { 
    public static void main(String[] args) { 
        Fruit[] fruit = new Apple[10];

        try { 
            fruit[0] = new Fruit(); // ArrayStoreException 
            fruit[0] = new Orange(); // ArrayStoreException 
        } catch(Exception e) { System.out.println(e); } 
    } 
}

基于Java documentation :

Thrown to indicate that an attempt has been made to store the wrong type of object into an array of objects.

我读过 here那个

When array is created it remembers what type of data it is meant to store.

如果数组记住它包含的数据类型,则意味着它知道它包含的数据类型。但是我发布的片段是正确编译的,所以在编译时数组显然不知道包含什么类型。

我的问题是:

  1. 为什么 ArrayStoreException 仅在运行时抛出?

  2. 编译器缺少哪些信息来意识到该赋值是不可能的?

  3. 是否存在此类代码正确而不会抛出 ArrayStoreException 的情况?

最佳答案

If the array remembers what type of data it contains, it means that it KNEW the type of data it contains.

在执行时,是的......就像在执行时一样,对象的类型是已知的:

Object x = "foo";
// The compiler won't let you call x.length() here, because the variable
// x is of type Object, not String.

另一种方法是让很多数组赋值隐式抛出一个已检查的异常。那太糟糕了 - 类似于检查 NullPointerException

What information are missing to the compiler to realise that that assignment is not possible?

如您所见,数组是协变的。当编译器看到对 AppleFruit[] 的赋值时,它不知道该数组的实际类型是什么成为。如果是 Fruit[]Apple[],那很好。如果它是 Orange[] 则不是。该信息仅在执行时出现 - 同样,就像编译器不知道表达式是否绝对不为空一样。

Is there any cases in which such code is correct so no ArrayStoreException is thrown?

好吧,如果你有一个包含最终类的编译时元素的数组,那么你就不能有任何更低的方差。例如:

public void foo(String[] array) {
    array[0] = "x";
}

这可能会因为 arraynull 或为空而抛出异常,但它永远不会抛出 ArrayStoreException,因为 String 是最终的。实现永远不能是 SubclassOfString[]

关于java - 为什么 ArrayStoreException 是 RuntimeException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38391161/

相关文章:

java - 无法找到或加载主类 org.apache.tools.ant.launch.launcher

java - 当 Path 是接口(interface)时创建路径对象?

c# - C# 中的(普通)throw 语句会导致异常吗?

java - Java 中 Thread 的自定义实现 : Is it possible though JNI?

java - Java GUI程序不会生成随机形状吗?

python - python 中的相交数组

java - 将按钮添加到数组

javascript - JS中如何判断是否设置了多维数组项?

java - "throws UncheckedException"是否有意义

java - PDFBox PDFMergerUtility : how do I tell which sources failed?