Are arrays being transformed when using an enhanced for loop?

北城余情 提交于 2019-12-13 18:36:46

问题


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
}

回答1:


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:

int[] x = new int[10]; // The value of x is a reference

int y = x[0]; // No boxing
Integer z = x[1]; // Boxing conversion from x[1] (which is an int) to Integer

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.




回答2:


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:

List<Integer> l = new ArrayList<Integer>();
l.add( 7 );
int i = l.get(0);

To be short hand for:

List<Integer> l = new ArrayList<Integer>();
Integer ii = Integer.valueOf( 7 )
l.add( ii );
int i = l.get(0).getIntValue();

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




回答3:


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:

The enhanced for statement has the form:

EnhancedForStatement:
    for ( VariableModifiersopt Type Identifier: Expression) Statement

The Expression must either have type Iterable or else it must be of an array type (§10.1), or a compile-time error occurs.

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.




回答4:


No.

Unlike primitives, arrays (and strings) are Objects.



来源:https://stackoverflow.com/questions/6216768/are-arrays-being-transformed-when-using-an-enhanced-for-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!