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

查看:193
本文介绍了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".

对于 ArrayList s(一般列出。由于运行时类型擦除,它实际上可以容纳任何对象。

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

以下操作在运行时抛出异常:

The following throws an exception when running:

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< String> 而不是 ArrayList ,编译时避免了这个问题-time:

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));

输出:


a

a

1

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

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