Is there a longer than int Java List?

后端 未结 3 850
谎友^
谎友^ 2020-12-19 16:47

I can\'t seem to find a Java List that\'s max length is long\'s max value.

Does such a List exist?

If so, where?

相关标签:
3条回答
  • 2020-12-19 17:17

    As List.get(int) accepts int as its argument, it is impossible to address entries with indexes greater than Integer.MAX_VALUE.

    Do note, however, that Iterable<?> or Map<Long, ?> can address much more data. As List implements Iterable it could contain any amount of data (that part being not exposed with int-based List's API).

    0 讨论(0)
  • 2020-12-19 17:33

    From the List documentation:

    int size()

    Returns the number of elements in this list. If this list contains more than Integer.MAX_VALUE elements, returns Integer.MAX_VALUE.

    So, even if a specific implementation of List holds Long.MAX_VALUE elements, you wouldn't know, using the standard List interface.

    I'm not sure if one exists, but my bet would be on LinkedList, since ArrayList is based on arrays, and those can't hold more than Integer.MAX_VALUE elements.

    0 讨论(0)
  • 2020-12-19 17:34

    As @afsantos says, the ArrayList class is inherently limited to Integer.MAX_VALUE entries because of the limitations of Java arrays.

    LinkedList doesn't have this limitation, but it is (nonetheless) expensive:

    • Each entry incurs an memory overhead of 2 references plus the size of an object header ... compared to just one reference for an array-based representation.

    • Indexing is an O(N) operation compared with O(1) for an array-based list.

    Here is a link to Java library that supports huge in-memory collections using direct mapped memory and/or encoding of the elements:

    • http://code.google.com/p/vanilla-java/wiki/HugeCollections

    There could be other alternatives out there.

    One could also envisage a "big" variant of regular array lists that used an array of arrays rather than a single array. But if you allow insertion into the middle of the list, it becomes difficult / expensive to achieve O(1) lookup. (That might be why I couldn't find an example with Google ...)

    0 讨论(0)
提交回复
热议问题