0
Can we set capacity to a arraylist
I want a arraylist[strings] with max capacity of 4 values
4 odpowiedzi
+ 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
thanks



