Do Java arrays have a maximum size?

前端 未结 9 2140
礼貌的吻别
礼貌的吻别 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 11:56

    Arrays are non-negative integer indexed , so maximum array size you can access would be Integer.MAX_VALUE. The other thing is how big array you can create. It depends on the maximum memory available to your JVM and the content type of the array. Each array element has it's size, example. byte = 1 byte, int = 4 bytes, Object reference = 4 bytes (on a 32 bit system)

    So if you have 1 MB memory available on your machine, you could allocate an array of byte[1024 * 1024] or Object[256 * 1024].

    Answering your question - You can allocate an array of size (maximum available memory / size of array item).

    Summary - Theoretically the maximum size of an array will be Integer.MAX_VALUE. Practically it depends on how much memory your JVM has and how much of that has already been allocated to other objects.

提交回复
热议问题