Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

max. length of List in Java

Tags:

java

list

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

like image 743
kandarp Avatar asked Dec 21 '10 11:12

kandarp


People also ask

Can you get the length of a list in Java?

You can use the size() method of java. util. ArrayList to find the length or size of ArrayList in Java. The size() method returns an integer equal to a number of elements present in the array list.

What is the length of an ArrayList?

ArrayList doesn't have length() method, the size() method of ArrayList provides the number of objects available in the collection. Array has length property which provides the length or capacity of the Array. It is the total space allocated during the intialization of the array.

What does list length do in Java?

Java List size() method returns the number of elements present in the ArrayList. For example, if an ArrayList has five string objects stored in it, the size method will return five.

How many values can a list hold?

A list can hold 1000 elements(as per the limit).


2 Answers

Integer.MAX_VALUE   

or heap which ever is low will be the limit

like image 54
jmj Avatar answered Oct 27 '22 01:10

jmj


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.

like image 37
dogbane Avatar answered Oct 26 '22 23:10

dogbane