Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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

  }  

    }
}
share|improve this question
    
As others already said, your program uses autoboxing a lot. To make this visual I usually enable the "hidden autoboxing" warnings or enable the "syntax colorer" in Eclipse. This prevents many surprising situations. –  Roland Illig Jul 24 '10 at 22:30
    
Thanks for the tip, Roland. I am using JCreator Pro 4.50 at the moment - I don't know if such a feature is available, I'll have a look through the settings to see what's there. –  The Thing Jul 24 '10 at 22:38

2 Answers 2

up vote 4 down vote accepted

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.

share|improve this answer

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.