<分区>
在创建数组时,我们可以传递short
、char
、byte
、int
。那么,[为什么] int[] a = new int['a']
有效?它不会引发编译时错误。
这种形式的数组声明是什么意思?
<分区>
在创建数组时,我们可以传递short
、char
、byte
、int
。那么,[为什么] 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).
因此,Byte
、Short
、Character
、Integer
、byte
中的任何一个>、short
、char
或 int
都是可以接受的。
因此 'a'
是一个字 rune 字,它是允许的,并且被提升为 int
值 97。
关于java - 创建新数组 : int[] a = new int "char"] 时使用 ['a',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52338897/