Using a long as ArrayList index in java

后端 未结 7 1523
遇见更好的自我
遇见更好的自我 2020-12-10 14:01

I am writing this java program to find all the prime numbers up to num using the Sieve of Eratosthenes, but when I try to compile, it says I can\'t use a long var as an arra

7条回答
  •  我在风中等你
    2020-12-10 14:50

    The Java specification limits arrays to at most Integer.MAX_VALUE elements. While a List may contain more elements (this is true for Collections in general), you can only add/get/remove/set them using an int index.

    Assuming you have the memory for that many elements (very unlikely I think), you could write your own data structure consisting of "concatenated" arrays. The get() and set() methods would take a long index and figure out the corresponding array and int index within that array.

    Also, I would suggest using booleans to represent the state of each number, instead of storing/removing each number explicitly. This would be better because (1) booleans take less space than longs, and (2) shifting elements (as done in ArrayList) during element removal can be expensive.

提交回复
热议问题