简体   繁体   中英

Why does unboxing occur in this case?

According to the Java Tutorial , the

Converting an object of a wrapper type (Integer) to its corresponding primitive (int) value is called unboxing. The Java compiler applies unboxing when an object of a wrapper class is:

  • Passed as a parameter to a method that expects a value of the corresponding primitive type.
  • Assigned to a variable of the corresponding primitive type.

Why does unboxing occur in this case?

char l = 0;
int arr[] = new int[]{1,2,3};
System.out.println(arr[new Integer(1)]);

Where in this scenario does either of those things happen? Is there an underlying method that governs element access in an array? Or does [] imply some sort of variable?

The JLS 15, §15.10.3 is pretty clear on this one:

...

The index expression undergoes unary numeric promotion ( §5.6 ). The promoted type must be int , or a compile-time error occurs.

...

Similar paragraphs can be found in older JLSes, eg JLS 8, §15.10.3 .

The unboxing occurs on line three

System.out.println(arr[new Integer(1)]);

arr is an array as declared on line two

int arr[] = int[]{1, 2, 3};

Note that the type of arr is an "array of int". All arrays accept an int for the index being accessed. In line 3, you are passing an Integer , these two types are not the same. One is a primitive type, while the other is an Object type. Since there exists a "unboxing conversion" to change the Integer to an int , unboxing occurs just before the value is passed as an index into the int array.

In (arr[new Integer(1)] the wrapper Integer gets converted to primitive type, because it is used as an array index.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM