gstackoverflow gstackoverflow - 3 months ago 13
Java Question

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

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?

nos nos
Answer

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();
    }
 }
Comments