Reputation: 13
What is the maximum number of elements an ArrayList
of Points
can store?
In other words, given this code:
ArrayList<Point> x = new ArrayList<>();
for (int i = 0; i < maxElements; i++) {
x.add(new Point(0, 0));
}
what is the maximum allowed value for maxElements
(given enough heap space) such that x.get(0)
is the correct value and is accessible?
Upvotes: 0
Views: 6419
Reputation: 7994
Integer.MAX_VALUE - 8
Since this is the maximum size of an ArrayList
Source: Line 191
Upvotes: 2
Reputation: 20534
Theoretically is 2^31, but practically it is depend on how mach memory do you have.
Upvotes: 0
Reputation: 6675
What is the maximum number of elements an ArrayList of Points can store?
ArrayList and Points are Objects and are stored in heap memory.If the heap memory can support,it can store a maximum of Integer.MAX_VALUE(2^31-1)
but you may get java.lang.OutOfMemoryError
before that.
What is the value of maxElements such that x.get(0) is the correct value and is accessible?
maxElements can have any value grater than equal to 1(so that it contains at least 1 element)
Upvotes: 0
Reputation:
The maxElements
could be a limit for the list. You can use x.size() > 0
check if you want x.get(0)
.
ArrayList<Points> x = new ArrayList<>();
for (int i = 0; i < maxElements; i++) {
x.add(new Point(0, 0));
}
Points p;
if (x.size() > 0)
p = x.get(0);
Upvotes: 0