为什么在这种情况下会发生拆箱?

Why does unboxing occur in this case?

根据Java Tutorial

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.

为什么在这种情况下会发生拆箱?

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

在这种情况下,这些事情发生在什么地方?是否存在管理数组中元素访问的底层方法?还是 [] 暗示某种变量?

(arr[new Integer(1)] 中,包装器 Integer 被转换为原始类型,因为它被用作数组索引。

第三行开箱

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

arr 是第二行声明的数组

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

请注意,arr 的类型是“整型数组”。对于正在访问的索引,所有数组都接受 int。在第 3 行,你传递了一个 Integer,这两种类型是不一样的。一种是原始类型,另一种是 Object 类型。由于存在将 Integer 更改为 int 的“拆箱转换”,因此拆箱发生在值作为索引传递到 int 数组之前。

JLS 15, §15.10.3 在这一点上非常清楚:

...

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

...

类似的段落可以在旧的 JLS 中找到,例如JLS 8, §15.10.3.