Search code examples
javaarrayslistfixed

How to implement a fixed size "list" in Java?


Since the Java core library doesn't have such a collection, would an array be the best option, especially if one doesn't want to rely on third-party libraries?


Solution

  • I'd write a wrapper class around an ArrayList, and in the add and addAll methods, I'd check for the list's size before adding new elements. If you have reached the maximum size, you can then throw an exception (or do nothing, depending on what you really want to do in your code).

    Here's a short example:

    public class SizeLimitedArray<E> implements java.util.List<E>
        {
        private static final int DEFAULT_SIZE_LIMIT = 10;
        private ArrayList<E> myList;
        private int maxSize;
    
        public SizeLimitedArray ()
            {
            this (DEFAULT_SIZE_LIMIT);
            }
    
        public SizeLimitedArray (int size)
            {
            myList = new ArrayList<E> (size);
            maxSize = size;
            }
    
        @Override
        public boolean add (E objectToAdd)
            {
            if (myList.size () > maxSize)
                {
                throw new IllegalStateException ("The array is full");
                }
    
            return myList.add (objectToAdd);
            }
    
        @Override
        public boolean addAll (Collection collectionToAdd)
            {
            if (myList.size () + collectionToAdd.size () > maxSize)
                {
                throw new IllegalStateException ("The array is full");
                }
    
            return myList.addAll (collectionToAdd);
            }
    
        // Rest of class omitted for brevity
        }