Do Java arrays have a maximum size?

前端 未结 9 2127
礼貌的吻别
礼貌的吻别 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

    Haven't seen the right answer, even though it's very easy to test.

    In a recent HotSpot VM, the correct answer is Integer.MAX_VALUE - 5. Once you go beyond that:

    public class Foo {
      public static void main(String[] args) {
        Object[] array = new Object[Integer.MAX_VALUE - 4];
      }
    }
    

    You get:

    Exception in thread "main" java.lang.OutOfMemoryError:
      Requested array size exceeds VM limit
    

提交回复
热议问题