Do Java arrays have a maximum size?

前端 未结 9 2139
礼貌的吻别
礼貌的吻别 2020-11-21 11:51

Is there a limit to the number of elements a Java array can contain? If so, what is it?

9条回答
  •  梦谈多话
    2020-11-21 12:08

    I tried to create a byte array like this

    byte[] bytes = new byte[Integer.MAX_VALUE-x];
    System.out.println(bytes.length);
    

    With this run configuration:

    -Xms4G -Xmx4G
    

    And java version:

    Openjdk version "1.8.0_141"

    OpenJDK Runtime Environment (build 1.8.0_141-b16)

    OpenJDK 64-Bit Server VM (build 25.141-b16, mixed mode)

    It only works for x >= 2 which means the maximum size of an array is Integer.MAX_VALUE-2

    Values above that give

    Exception in thread "main" java.lang.OutOfMemoryError: Requested array size exceeds VM limit at Main.main(Main.java:6)

提交回复
热议问题