java - 创建新数组 : int[] a = new int "char"] 时使用 ['a'

标签 java arrays

<分区>

在创建数组时,我们可以传递shortcharbyteint。那么,[为什么] int[] a = new int['a'] 有效?它不会引发编译时错误。

这种形式的数组声明是什么意思?

最佳答案

来自 JLS Sec 15.10.1 :

The type of each dimension expression within a DimExpr must be a type that is convertible (§5.1.8) to an integral type, or a compile-time error occurs.

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

来自JLS Sec 5.6.1 :

If the operand is of compile-time type Byte, Short, Character, or Integer, it is subjected to unboxing conversion (§5.1.8). The result is then promoted to a value of type int by a widening primitive conversion (§5.1.2) or an identity conversion (§5.1.1).

Otherwise, if the operand is of compile-time type byte, short, or char, it is promoted to a value of type int by a widening primitive conversion (§5.1.2).

因此,ByteShortCharacterIntegerbyte 中的任何一个>、shortcharint 都是可以接受的。

因此 'a' 是一个字 rune 字,它是允许的,并且被提升为 int 值 97。

关于java - 创建新数组 : int[] a = new int "char"] 时使用 ['a',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52338897/

相关文章:

javascript - .length 是否适合调用 JavaScript 数组?

javascript - 我必须创建一个函数,它返回传入的数组的最后一个元素

javascript - 如何在 JavaScript 中转换和重新排序数组?

java - 为什么我的 Java 程序忽略另一个 html 中的列表?

java - 如何解析不带引号的 JSON 字符串

java - 如何在 javafx 中正确缩放控件和布局

java - mp4parser 版本冲突(压缩后的视频没有声音)

java - 如何找到字符串中单词的精确匹配

javascript - 从后面将字符串拆分为数组

php - 如何使用数组插入多个数据