Using for-each over an array of Objects - "Integer[] array" - Why Does "for(int i : array)" Work?
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);
}
Sys开发者_如何学Gotem.out.print("\n");
for(int i : array)
{
System.out.print(i);
}
}
}
It's auto-unboxing, that's all. There's no need for iterating over anything to demonstrate that:
Integer x = 10;
int y = x;
From the Java Language Specification, section 5.1.8:
Unboxing conversion converts values of reference type to corresponding values of primitive type.
(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.
It's because for the Java base types (int
, byte
, short
, etc.), it performs "autoboxing" and autounboxing.
When you take the object out of the collection, you get the Integer that you put in; if you need an int, you must unbox the Integer using the intValue method. All of this boxing and unboxing is a pain, and clutters up your code. The autoboxing and unboxing feature automates the process, eliminating the pain and the clutter.
精彩评论