Can we set capacity to a arraylist | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Can we set capacity to a arraylist

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

30th May 2018, 3:52 PM
Elvis Edison
Elvis Edison - avatar
4 Answers
+ 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.
30th May 2018, 5:12 PM
Dan Walker
Dan Walker - avatar
+ 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
30th May 2018, 5:26 PM
Dan Walker
Dan Walker - avatar
0
thanks
25th Jul 2018, 9:09 AM
Elvis Edison
Elvis Edison - avatar