max. length of List in Java

前端 未结 3 1062
半阙折子戏
半阙折子戏 2021-01-11 17:10

What is the maximum length of List in java? I mean that how many maximum elements can store in list?

相关标签:
3条回答
  • 2021-01-11 18:02
    Integer.MAX_VALUE   
    

    or heap which ever is low will be the limit

    0 讨论(0)
  • 2021-01-11 18:07

    This depends on the specific list implementation. Most people think it's Integer.MAX_VALUE but it isn't limited to that. In fact the documentation of the size() method merely states:

    If this list contains more than Integer.MAX_VALUE elements, returns Integer.MAX_VALUE.

    So it might as well contain more elements.

    0 讨论(0)
  • 2021-01-11 18:10

    It's very likely that you will run out of heap space well before you get anywhere close to Integer.MAX_VALUE number of elements, but let's see what would happen if we had infinite memory and tried to add more than Integer.MAX_VALUE elements to a List:

    1) ArrayList:

    An ArrayList will try to increase its capacity:

    int newCapacity = (oldCapacity * 3)/2 + 1;
    

    This calculation will overflow and newCapacity will actually be less than Integer.MAX_VALUE. The ArrayList will then try to copy the elements in the original array to a smaller array and will hence lose elements.

    2) LinkedList:

    A LinkedList works a bit better once you cross the Integer.MAX_VALUE limit. It will continue to hold elements, however the size attribute will suffer from integer overflow and will affect other operations that make use of it.

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