为什么自动装箱在数组中不起作用? [英] Why autoboxing doesn't work in arrays?

查看:29
本文介绍了为什么自动装箱在数组中不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不明白为什么这段代码不能编译:

I don't understand why this code is not compiling:

 Object[] arr = new int[3];

我不需要此代码即可工作.我只想了解原因为什么自动装箱在这种情况下不起作用?

I don't need this code to work. I just want to understand the reason why autoboxing desn't work in this case?

推荐答案

装箱将原始类型的实例转换为相应包装器类型的实例.

Boxing converts an instance of a primitive type to an instance of the corresponding wrapper type.

它不适用于数组类型.

为什么?

  • 因为这就是语言设计者设计 Java 的方式,也是 JLS 指定的内容.详情在 JLS 5.1.7.

JLS 作者没有解释这个决定.但是,原因有很多.这里有几个比较明显的.

The JLS authors did not include an explanation for this decision. However, there are a number of reasons. Here are couple of the more obvious ones.

  • 效率.将 int[] 转换为 Object[] 需要访问和转换数组的所有元素.这是昂贵的(O(N))......而不是应该隐藏在某些语法背后的程序员.

  • Efficiency. Converting an int[] to an Object[] entails visiting and converting all elements of the array. That is expensive (O(N)) ... and not something that should be hidden from the programmer behind some syntax.

将数组装箱必然会创建一个与原始数组本质上不同的新数组.您可以通过以下方式说明这一点:

Boxing an array would necessarily create a new array that is inherently different to the original one. You would be able to tell this in the following:

int[] ints = new int[]{1,2,3};
Integer[] arr = ints;  // hypothetical boxing of the elements
// What does ints.equals(arr) return?

array[1] = 0;
// What does ints[0] contain now?

相比之下,(真实的)装箱和拆箱转换只有在比较指针时才能区分的值......即使如此,也不可靠.

By contrast, (real) boxing and unboxing converts between values that are only distinguishable if you compare pointers ... and even then, not reliably.

最重要的是,扩展装箱和拆箱会引入难以解决的效率和概念问题.

The bottom line is that extending boxing and unboxing would introduce both efficiency and conceptual problems that would be hard to resolve.

这篇关于为什么自动装箱在数组中不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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