Can we set capacity to a arraylist | Sololearn: Learn to code for FREE!


Can we set capacity to a arraylist

I want a arraylist[strings] with max capacity of 4 values

5/30/2018 3:52:07 PM

Elvis Edison

4 Answers

New Answer



ArrayList is designed to resize dynamically, so you can set an initial capacity but this can resize if you try to add more. You could wrap a class around it that can perform this check: public class FixedCapacityList<T> { private int maxSize; private ArrayList<T> dataList; // constructor public FixedCapacityList(int size) { maxSize = size; dataList = new ArrayList<>(size); } public boolean add(T data) { if (dataList.size() >= maxSize) { return false; } else { return dataList.add(data); } } So this class wraps an ArrayList and stops you adding more than the desired amount of data. You could throw an exception if you want instead.

+2 in fact, since the class is not final you could just extend it and override the add method to not allow more than the number of elements you want