Can you index an array with a long int?

前端 未结 3 2030
滥情空心
滥情空心 2020-12-18 22:09

Is it somehow possible to use a long int to index an array? Or is this not allowed?

What I mean is bellow in the code.

long x = 20;
char[] array = ne         


        
3条回答
  •  生来不讨喜
    2020-12-18 22:23

    No, it's not possible. JLS 15.10 states that the expression in an array initializer must be promoted to an int:

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

    Same thing with applies to array access expressions (JLS 15.13):

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

    If you want to use a long, you'll have to cast it to int first:

    char[] array = new char[(int) x];
    res = array[(int) x];
    

提交回复
热议问题