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

0

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

+11

https://stackoverflow.com/questions/3564837/capacity-of-arraylist

+2

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

https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html 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

0