有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

无法在java中使用长值初始化布尔数组?

我要做的是初始化布尔数组,数组的大小是长值

public static  List<Integer> primesUpTo(long target) {

         boolean[] nonPrime = new boolean[target];

}

我遇到以下错误:

possible loss of precision
         boolean[] nonPrime = new boolean[target];
                                          ^
  required: int
  found:    long

有人能解释一下为什么我不能使用长值初始化布尔数组,也不能增加长值,比如:Boolean[]nonPrime=new Boolean[target+1]也不工作。谢谢你提前通知


共 (1) 个答案

  1. # 1 楼答案

    这是一种语言限制

    Java has been criticized for not supporting arrays of more than 2^31−1 (about 2.1 billion) elements.[17][18][19] This is a limitation of the language; the Java Language Specification, Section 10.4, states that:

    Arrays must be indexed by int values... An attempt to access an array component with a long index value results in a compile-time error.[20]

    https://en.m.wikipedia.org/wiki/Criticism_of_Java#Large_arrays

    在这里可以找到答案:Do Java arrays have a maximum size?