加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – 为什么ArrayStoreException是RuntimeException?

发布时间:2020-12-15 04:35:09 所属栏目:Java 来源:网络整理
导读:假设我们有以下程序: 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
假设我们有以下程序:

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.

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

我的问题是:

>为什么仅在运行时抛出ArrayStoreException?
>编译器缺少哪些信息才能意识到该分配是不可能的?
>是否存在此类代码正确的情况,因此不会抛出ArrayStoreException?

解决方法

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

该数组“仅记住”它在运行时实际包含的类型.

首先声明数组,在本例中是一个Fruit数组.

然后创建数组,在本例中为Apple数组.

在运行时进行创建,但编译器仅用于验证仅为数组分配了声明类型的对象.在运行时期间可能会发生很多事情.

请考虑以下代码:

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];
        boolean alt = (Math.random() < 0.5);

        try { 
            fruit[0] = fruitFactory(alt); 
        } catch(Exception e) { System.out.println(e); } 
    } 

    private static Fruit fruitFactory(boolean apple) {
        if (apple) {
            return new Apple();
        } else {
            return new Orange();
        }
    } 
}

除了通过fruitFactory方法为fruit [0]赋值之外,代码与您的代码相同.编译器无法判断boolean alt是真还是假.

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

如上所述 – 编译器无法判断分配是否可行.

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

是的,在上面代码的50%的情况下.您必须验证分配的对象是否与数组相同或捕获异常.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读