It depends on the List implementation. Since you index arrays with ints, an ArrayList can't hold more than Integer.MAX_VALUE elements. A LinkedList isn't limited in the same way, though, and can contain any amount of elements.

Edit: I realize this sounds like an endorsement of LinkedList. But please note that although they don't have a theoretical capacity limit, linked lists are usually an inferior choice to array-based data structures because of higher memory use per element (which lowers the list's actual capacity limit) and poor cache locality (because nodes are spread all over RAM). It's definitely not the data structure you want if you have more items than can be crammed into an array.

Answer from gustafc on Stack Overflow
Discussions

java - What is the maximum value of index of an ArrayList? - Software Engineering Stack Exchange
I was thinking about it. You may have access to endless memory (one computer with lot of RAM) so that you can keep on adding more and more elements to your ArrayList. But, I think that you can only More on softwareengineering.stackexchange.com
🌐 softwareengineering.stackexchange.com
March 18, 2013
java - ArrayList Limit to hold 10 Values - Stack Overflow
I am using an ArrayList within my code which gets populated by a EditText field but I am wanting to limit the ArrayList so it can only hold 10 values. After 10 values have been added if another tri... More on stackoverflow.com
🌐 stackoverflow.com
December 3, 2012
java - Any way to set max size of a collection? - Stack Overflow
The OP asks for limiting the maximun size. 2012-11-09T19:04:03.803Z+00:00 ... Here is my own code for an ArrayList with a maximum size, build from Matthew Gilliard's answer. It overrides all three constructors from ArrayList, and also overrides .AddAll(). import java.util.ArrayList; import ... More on stackoverflow.com
🌐 stackoverflow.com
how to set a maximum size for ArrayList? - Processing Forum
I m creating a particles system, with array list, i want to add particles but when they get to 100 i want them to die. How to do it. ... Use an if statement and the size() of the ArrayList. More on forum.processing.org
🌐 forum.processing.org
May 20, 2013
🌐
Coderanch
coderanch.com › t › 524745 › java › Maximum-capacity-arrayList-String-objects
Maximum capacity of arrayList for String objects is one million? (Java in General forum at Coderanch)
January 24, 2011 - Even when I explicitly declare ... hold 1 million String objects. Should I be using another data structure? I really would like to use arrayList, unless it is impossible to store this much data in it. Thanks. ... No, the maximum capacity of an ArrayList (or any kind of list whatsoever) is limited only by the amount of memory the JVM has available...
🌐
BeginnersBook
beginnersbook.com › 2013 › 12 › java-arraylist-trimtosize-method-example
Java ArrayList trimToSize() Method example
import java.util.ArrayList; public class Main { public static void main(String[] args) { // Creating an ArrayList with initial capacity of 100 ArrayList<Integer> list = new ArrayList<>(100); // Adding elements to the list list.add(11); list.add(22); list.add(33); list.add(44); list.add(55); System.out.println("Size of list: " + list.size()); System.out.println("Capacity before trimToSize: " + getCapacity(list)); // Trim the capacity to the current size list.trimToSize(); System.out.println("Capacity after trimToSize: " + getCapacity(list)); } // This method prints the current capacity of ArrayList private static int getCapacity(ArrayList<?> list) { try { java.lang.reflect.Field field = ArrayList.class.getDeclaredField("elementData"); field.setAccessible(true); return ((Object[]) field.get(list)).length; } catch (Exception e) { e.printStackTrace(); return -1; } } }
🌐
Javaprogramto
javaprogramto.com › 2021 › 12 › java-list-or-arraylist-max-size.html
Java List or ArrayList Max Size (With Examples) JavaProgramTo.com
December 22, 2021 - That means you can not use the ArrayList with max size as Integer.MAX_VALUE. This itself is not able to create the array with the size of the max value. That's why we got the error "java.lang.OutOfMemoryError: Requested array size exceeds VM limit". In this article, We've seen How much data can a List can hold at the maximum in java?
Top answer
1 of 11
27

You can do this:

List<X> list = Arrays.asList(new X[desiredSize]);
// where X is any Object type (including arrays and enums,
// but excluding primitives)

The resulting list is modifiable, but not resizable (i.e. add(e) and remove(e) don't work, but set(index, e) does).

Reference:

  • Arrays.asList(T ...)

Or: using Guava, here's a static method that decorates an existing List with a maximum size

public static <T> List<T> setMaxSize(
    final List<T> input, final int maxSize){

    return new ForwardingList<T>(){

        @Override
        public boolean addAll(Collection<? extends T> collection){
            return standardAddAll(collection);
        }

        @Override
        public boolean addAll(int index, Collection<? extends T> elements){
            return standardAddAll(index, elements);
        }

        public boolean add(T e) {
            checkMaxSize();
            return delegate().add(e);
        }

        @Override
        public void add(final int index, final T e){
            checkMaxSize();
            delegate().add(index, e);
        }

        private void checkMaxSize(){
            if(size() >= maxSize){
                throw new UnsupportedOperationException("Maximum Size "
                    + maxSize + " reached");
            }
        }

        @Override
        protected List<T> delegate(){
            return input;
        }
    };
}

Since ForwardingXxx classes exist for all standard collection types, you can write yourself similar decorators for other collections as well.

Obviously this will only work if your client code uses the decorated collection. If you change the underlying collection you are screwed (just like the Collections.unmodifiableXXX methods)

Reference:

  • ForwardingList
2 of 11
9

ArrayBlockingQueue and LinkedBlockingQueue both support a maximum size. LinkedHashMap supports eviction of the oldest or least-recently-used items when reaching a maximum size.

What do you want it to do when the maximum size is reached?

Find elsewhere
🌐
Processing Forum
forum.processing.org › topic › how-to-set-a-maximum-size-for-arraylist
how to set a maximum size for ArrayList? - Processing Forum
May 20, 2013 - I m creating a particles system, with array list, i want to add particles but when they get to 100 i want them to die. How to do it. ... Use an if statement and the size() of the ArrayList.
🌐
HowToDoInJava
howtodoinjava.com › home › java 8 › java stream limit()
Java Stream limit() with Example - HowToDoInJava
March 30, 2022 - The limit(N) method returns first N elements in the encounter order of the Stream. The skip(N) discards the first N elements of the Stream. List<Integer> list = Stream.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) .skip(6) .collect(Collectors.toList()); ...
🌐
CodingTechRoom
codingtechroom.com › question › -limit-entries-java-list
How Can You Limit the Number of Entries in a Java List? - CodingTechRoom
While Java itself does not impose a strict limit on the size of List implementations (such as ArrayList or LinkedList), you can implement your own logic to enforce a maximum size.
🌐
Lucazanini
lucazanini.eu › 2015 › java › a-list-with-a-fixed-size
A List with a fixed size – Luca Zanini
November 15, 2015 - There isn’t a class that extends List for which you can set a limit on its size and that it behaves like a Queue object if you add an item beyond its fixed size. ... with a maximum number of elements, beyond which, if you add other elements, the class behaves like a queue with a FIFO logic (first-in first-out) ... import java...
🌐
Baeldung
baeldung.com › home › java › java array › the capacity of an arraylist vs the size of an array in java
The Capacity of an ArrayList vs the Size of an Array in Java | Baeldung
November 11, 2025 - Technically, the default capacity (DEFAULT_CAPACITY) of a newly created ArrayList is 10. However, Java 8 changed how this initial capacity is used for performance reasons. It’s not used immediately and is guaranteed lazily once a new item ...
Top answer
1 of 15
65

This should do it if memory serves:

List<MyType> fixed = Arrays.asList(new MyType[100]);
2 of 15
36

A Java list is a collection of objects ... the elements of a list. The size of the list is the number of elements in that list. If you want that size to be fixed, that means that you cannot either add or remove elements, because adding or removing elements would violate your "fixed size" constraint.

The simplest way to implement a "fixed sized" list (if that is really what you want!) is to put the elements into an array and then Arrays.asList(array) to create the list wrapper. The wrapper will allow you to do operations like get and set, but the add and remove operations will throw exceptions.

And if you want to create a fixed-sized wrapper for an existing list, then you could use the Apache commons FixedSizeList class. But note that this wrapper can't stop something else changing the size of the original list, and if that happens the wrapped list will presumably reflect those changes.


On the other hand, if you really want a list type with a fixed limit (or limits) on its size, then you'll need to create your own List class to implement this. For example, you could create a wrapper class that implements the relevant checks in the various add / addAll and remove / removeAll / retainAll operations. (And in the iterator remove methods if they are supported.)

So why doesn't the Java Collections framework implement these? Here's why I think so:

  1. Use-cases that need this are rare.
  2. The use-cases where this is needed, there are different requirements on what to do when an operation tries to break the limits; e.g. throw exception, ignore operation, discard some other element to make space.
  3. A list implementation with limits could be problematic for helper methods; e.g. Collections.sort.
🌐
TheServerSide
theserverside.com › blog › Coffee-Talk-Java-News-Stories-and-Opinions › Java-array-size-explained-by-example
Java array size, length and loop examples
Thus, the maximum number of elements a Java array can hold is typically a little less than the upper limit of a Java int. In Java, once you set the Java array size it is fixed, and it can’t be changed. This puts Java in sharp contrast to other programming languages like JavaScript where arrays resize dynamically. But in Java, once the array size is set, it is permanent. However, there are collection classes in Java that act like a Java array but resize themselves automatically. Any class that extends the List interface expands dynamically.
🌐
Upgrad
upgrad.com › home › tutorials › software & tech › java list size
Java List Size: Understanding and Utilizing Dynamic Data Structures
6 days ago - The capacity refers to the maximum number of elements the ArrayList can hold without resizing, while the size represents the actual number of elements currently stored in the ArrayList. The time complexity of the Java List size() method is constant, denoted as O(1).
🌐
ConcretePage
concretepage.com › java › java-8 › java-stream-limit
Java Stream limit()
May 8, 2024 - Stream.of("A", "B", "C", "D").limit(10) .forEach(s->System.out.println(s)); We can see that source stream has 4 elements whereas we are calling limit with max size 10. Here limit will return stream with all elements and the output will be A ...
🌐
Flowstopper
flowstopper.org › 2013 › 01 › java-sublist-for-offset-and-limit.html
Java subList() for offset and limit - Flowstopper
} if (limit >-1) { //apply offset and limit return list.subList(offset, Math.min(offset+limit, list.size())); } else { //apply just offset return list.subList(offset, list.size()); } } else if (limit >-1) { //apply just limit return list.subList(0, Math.min(limit, list.size())); } else { return list.subList(0, list.size()); } } Posted by · Unknown at · 3:55 AM · Email ThisBlogThis!Share to XShare to FacebookShare to Pinterest · Labels: java ·