使用增强型 for 循环时数组是否会被转换?
Java 5 或更高版本是否对数组应用某种形式的“装箱”?当下面的代码像 Iterable 一样遍历数组时,我想到了这个问题。
for( String : args ){
// Do stuff
}
Does Java 5 or higher apply some of form of "boxing" to arrays? This question came to mind as the following code goes through an array as if it's an Iterable.
for( String : args ){
// Do stuff
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
数组不是基元。基元是不是对象的东西。只有 boolean、char、byte、short、int、long、float 和 double 是原语。数组是具有特殊语法的对象。如果你可以在 Java 中的类型上调用 toString() < 5.它并不原始。
所有自动装箱所做的就是将基元与需要对象(例如 ArrayList)的对象相互转换。它允许这样的代码:
简写为:
这就是自动装箱所做的一切。由于 String 已经是一个对象(与 C 中不同的是,它不等于 char[]),因此无需对 String 进行装箱/拆箱。
编辑:如上所述添加布尔值
Arrays are not primitives. Primitives are things that are not objects. Only boolean, char, byte, short, int, long, float, and double are primitives. Arraysare objects with special syntax. If you can call toString() on type in Java < 5 it is not primitive.
All autoboxing does is convert primitives to/from objects that expect objects such as ArrayList. It allows code like:
To be short hand for:
This is all autoboxing does. Since String is already an object (and is not equivalent to char[] unlike in C) there is nothing to box/unbox String to.
Edit: added boolean as mentioned
由于您似乎特别想知道增强的 for 循环,答案是它们是特殊情况的,而不是拆箱的。来自 §14.14.2:
事实上,如果表达式是一个数组,它会被转换为等效的索引 for 循环,而不是实际使用迭代器。语言规范的同一部分涵盖了精确的扩展。
Since you seem to be wondering about enhanced for loops in particular, the answer is that they are special-cased, not unboxed. From §14.14.2:
In fact, if the expression is an array, it is translated into the equivalent indexed for loop rather than actually using an iterator. The precise expansions are covered in the same section of the language spec.
不,数组始终是引用类型。不需要装箱或拆箱,除非它是针对每个元素的访问。例如:
另请注意,虽然增强的 for 循环可用于数组和可迭代对象,但它们的编译方式有所不同。
请参阅第 14.14.2 节 JLS 用于增强 for 循环的两种不同翻译。
No, arrays are always reference types. There's no need for boxing or unboxing, unless it's on the access for each element. For example:
Also note that although the enhanced for loop is available for both arrays and iterables, it's compiled differently for each.
See section 14.14.2 of the JLS for the two different translations of the enhanced for loop.
不。
与基元不同,数组(和字符串)是
对象
。No.
Unlike primitives, arrays (and strings) are
Object
s.