在对象数组上使用 for-each - “Integer[] array” - 为什么“for(int i : array)”工作?
当我循环对象数组时,为什么在第二个“for-each”循环中使用原始数据类型可以工作。是否有在幕后发生的转换回 Integer 对象的原始等价物?
import java.util.Arrays;
import java.util.Collections;
public class CodeTestingClass
{
public static void main(String[] args)
{
Integer[] array = {1,2,3,4,5};
Collections.rotate(Arrays.asList(array), 1);
System.out.println(Arrays.toString(array) + "\n" );
for(Integer i : array)
{
System.out.print(i);
}
System.out.print("\n");
for(int i : array)
{
System.out.print(i);
}
}
}
Why does using a primitive data type work in the second "for-each" loop when I am looping over an array of objects. Is there a casting back to the primitive equivalent of the Integer object occurring behind the scenes?
import java.util.Arrays;
import java.util.Collections;
public class CodeTestingClass
{
public static void main(String[] args)
{
Integer[] array = {1,2,3,4,5};
Collections.rotate(Arrays.asList(array), 1);
System.out.println(Arrays.toString(array) + "\n" );
for(Integer i : array)
{
System.out.print(i);
}
System.out.print("\n");
for(int i : array)
{
System.out.print(i);
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
就是自动拆箱,仅此而已。无需迭代任何内容即可证明这一点:
根据 Java 语言规范,第 5.1.8 节:
(那里还有更多详细信息,但主要只是转换列表。)
第 5.2 节 指出拆箱转换在赋值转换的上下文中可用。
It's auto-unboxing, that's all. There's no need for iterating over anything to demonstrate that:
From the Java Language Specification, section 5.1.8:
(There are a few more details there, but it's mostly just the list of conversions.)
Section 5.2 calls out unboxing conversions as being available in the context of assignment conversions.
这是因为对于 Java 基本类型(
int
、byte
、short
等),它执行“自动装箱" 和自动拆箱。It's because for the Java base types (
int
,byte
,short
, etc.), it performs "autoboxing" and autounboxing.