Java 数组是同构的,而 ArrayLists 不是,这意味着什么? [英] What does it mean that Java arrays are homogeneous, but ArrayLists are not?

查看:24
本文介绍了Java 数组是同构的,而 ArrayLists 不是,这意味着什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我们有一个 Type[],我们只能在其中存储 Type 或其子类型.ArrayList 也是如此.那么为什么说一个是同质的,而另一个则不是?

If we have a Type[], we can only store Type or its subtypes in it. The same goes for ArrayList. So why is it said that one is homogeneous while the other is not?

推荐答案

数组对添加元素的类型进行运行时检查.也就是说,如果添加了一个不同类型的新元素,一个 ArrayStoreException 在运行时抛出.这就是为什么他们被认为是本土的".

Arrays have a runtime check on the type of the added element. That is, if a new element that is not of the same type is added, an ArrayStoreException is thrown at runtime. That's why they are considered as "homegeneous".

对于ArrayLists(通常是Lists)来说,情况并非如此.由于运行时的类型擦除,它实际上可以容纳任何对象.

This is not true for ArrayLists (Lists in general). Due to type erasure at runtime, it can practically hold any object.

以下运行时抛出异常:

Object[] array = new String[3];
array[0] = "a";
array[1] = 1;   // throws java.lang.ArrayStoreException

不像以下编译和运行没有问题(尽管编译器警告,因为它没有正确使用泛型):

unlike the following which compiles and runs without problem (although with a compiler warning as it doesn't properly use generics):

ArrayList list = new ArrayList<String>();
list.add("a");
list.add(1);    // OK
list.add(new Object());  // OK

正确使用泛型,即声明上面类型ArrayList而不是ArrayList的变量list,问题是在编译时避免:

With a correct use of generics, i.e. declaring the variable list above of type ArrayList<String> instead of ArrayList, the problem is avoided at compile-time:

ArrayList<String> list = new ArrayList<String>();
list.add("a");
list.add(1);  // compilation error
list.add(new Object());  // compilation error

但即使使用通用声明的列表,您也可以在运行时毫无例外地进行类似的工作:

But even with a generically declared list, you can have something like this work without an exception at runtime:

ArrayList<String> list = new ArrayList<String>();
list.add("a");
Method[] methods = List.class.getMethods();
for(Method m : methods) {
    if(m.getName().equals("add")) {
        m.invoke(list, 1);
        break;
    }
}
System.out.println(list.get(0));
System.out.println((Object) list.get(1));

输出:

一个

1

这篇关于Java 数组是同构的,而 ArrayLists 不是,这意味着什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆