How can I find out the size of a java.util.List if the actual size is greater than the Integer.MAX_VALUE?

StackOverflow https://stackoverflow.com/questions/22931808

  •  29-06-2023
  •  | 
  •  

As I understood java.util.List does not have size restrictions. As I understand, the size() method:

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

Therefore I have following question:

If my List has a size that is larger than the Integer.MAX_VALUE, is there a way to determine the exact size?

有帮助吗?

解决方案

You would need to count them yourself, using a bigger data type.

long realSize;

if (myList.size() < Integer.MAX_VALUE) {
    realSize = myList.size();
} else {
    realSize = Integer.MAX_VALUE;
    ListIterator<Foo> iter = myList.listIterator(Integer.MAX_VALUE);
    while (iter.hasNext()) {
      realSize++;
      iter.next();
    }
 }

其他提示

It would depend on the specific implementation of List you are using. For example ArrayList uses a java array internally, which has a max size of Integer.MAX_VALUE - 5. Other implementations of List might have different max sizes.

If a list supports sizes that huge, it will almost certainly support some sort of alternate size method you can use to get the size as a long. For example, the first such implementation I found, HugeCollections, has a longSize method. The overhead of trying to get the true size without such a method is simply absurd.

I don't think any standard library List implementation supports sizes that huge; ArrayList and LinkedList don't. If you ever need to deal with this kind of problem, the documentation for the giant list type you're using should tell you what to do.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top