Is there a longer than int Java List?

2019-01-28 18:49发布

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条回答
兄弟一词,经得起流年.
2楼-- · 2019-01-28 18:59

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:

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 ...)

查看更多
Anthone
3楼-- · 2019-01-28 19:04

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).

查看更多
等我变得足够好
4楼-- · 2019-01-28 19:05

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.

查看更多
登录 后发表回答