开发者

ArrayList trimtosize not working android

开发者 https://www.devze.com 2023-04-01 12:41 出处:网络
Am having an arraylist and its code is: ArrayList<String> recentdata=new ArrayList<String>();

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.开发者_StackOverflowtrimToSize();
}

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


Size and capacity are two different things.

Say you have this:

ArrayList<String> data = new ArrayList<String>(5);

Your capacity is 5, but the size is 0.

Then you add some data:

data.add("hello");

Then you call trimToSize:

data.trimToSize();

Your size and capacity are both now 1.

What exactly are you trying to do? There is probably a better way to do it :)


trimToSize doesn't remove any element from the list. From the javadoc:

Trims the capacity of this ArrayList instance to be the list's current size. An application can use this operation to minimize the storage of an ArrayList instance.

The capacity is the size of the array used by the ArrayList internally. If your list contains 6 elements and has a capacity of 10, the last 4 elements of the array are null. Calling trimToSize will 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号