Am having an arraylist and its code is:
ArrayList<String> recentdata=new ArrayList<String>();
I want to limit the size of ArrayList to a specific size i.e. 5 in my case, when it reaches to that number.
That means 0 to 5 it works as ArrayList, when it reaches to that 5, I want to stop the growth of ArrayList.
For that am using: to set the size
if(recentdata.size() >= 5) {
recentdata.trimToSize();
}
but its not working i.e., size growth is not stopping it goes 6,7 etc.
How to do this? anyother way to do this? or what is wrong in my approach?
Thanks
trimToSizedoesn’t remove any element from the list. From the javadoc:The capacity is the size of the array used by the
ArrayListinternally. If your list contains 6 elements and has a capacity of 10, the last 4 elements of the array are null. CallingtrimToSizewill just make the list use an array of 6 instead of 10.Just don’t add anything to the list once its size is 5, instead of adding, and then trying to remove.