how to take large size array in java

后端 未结 6 1185
醉话见心
醉话见心 2021-01-26 07:05

i am new to java and i want to take large input size array in java. but in gives me some Runtime Error - NZEC, I don\'t know about it and i also did some research on this error

6条回答
  •  旧时难觅i
    2021-01-26 07:26

    As the other answers suggested, array-indexes are int-based, and an array is probably not the right data structure for whatever it is you want to do.

    Let's consider memory usage. An array has a 12 byte object header, followed by n * v bytes for the actual data (where n is the array size, and v the size of the type you're storing in it).

    For example, let's consider the following array declaration:

    long[] longArray = new long[Integer.MAX_VALUE];
    

    A long has 64 bits, or 8 bytes. Integer.MAX_VALUE equals 2147483647. This means your array is going to take 17179869188 bytes, or in other words 17 GB of RAM.

    Is it possible to create larger arrays? Definitely: you could make a multi-dimensional array (each additional dimension would multiply the available positions by up to Integer.MAX_VALUE), but the memory usage will be atrocious. Consider the following example:

    long[] multiArray = new long[5][5];
    

    This array has 25 positions, so by my earlier formula you might figure it takes 25 * 8 + 12 bytes, or 212 bytes, but a 2-dimensional array is an array of arrays, so each inner array also has an object header, so we're talking (5 * 8 + 12) * 5 + 12 bytes, or 272 bytes. Now imagine doing this on larger levels.

    long[] multiArray = new long[Integer.MAX_VALUE][Integer.MAX_VALUE];
    

    This takes (Integer.MAX_VALUE * 8 + 12) * Integer.MAX_VALUE + 12 bytes, or 3.689348813882917e19 bytes (36.89 exabytes, or 36.89 billion GB).

    If you really need to work with those amounts of data, you probably need a computing cluster, not an array.

提交回复
热议问题