Search code examples
javalistcollections

Define a fixed-size list in Java


Is it possible to define a list with a fixed size that's 100? If not why isn't this available in Java?


Solution

  • FixedSizeList

    Yes,

    The Apache Commons library provides the FixedSizeList class which does not support the add, remove and clear methods (but the set method is allowed because it does not modify the List's size). Ditto for FixedSizeList in Eclipse Collections. If you try to call one of these methods, your list remains the same size.

    To create your fixed size list, just call

    List<YourType> fixed = FixedSizeList.decorate(Arrays.asList(new YourType[100]));
    

    You can use unmodifiableList if you want an unmodifiable view of the specified list, or read-only access to internal lists.

    List<YourType> unmodifiable = java.util.Collections.unmodifiableList(internalList);