java - 为什么会出现这种情况下拆箱的情况呢?

标签 java arrays indexing jls unboxing

根据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)]);

在这种情况下,这些事情会在哪里发生?是否有管理数组中元素访问的底层方法?或者 [] 是否暗示某种变量?

最佳答案

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 .

关于java - 为什么会出现这种情况下拆箱的情况呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65372253/

相关文章:

sql - 从数组中删除一个非唯一值

sql-server - 在 SQL Server 中对大表进行分区或索引

c# - c#中的动态数组

java - `Rectangle2D.Double` 如何知道它应该在对 `JOptionPane` 的调用中显示在 `paintIcon()` 内?

java - Hibernate 重复数据库条目

java - 为什么当 if 参数在 java 中已经设置为 true 时, if 的 else case 不会产生任何错误

javascript - 反转数组,让新数组中的元素与原始数组元素的长度相等 - JavaScript

mysql - 我应该索引什么?用户名还是用户 ID?

mysql - 导入 sql 文件索引到位后,但实际上没有索引

java - 二进制转十六进制