I often use Lists in my Android applications. Right now I am creating a Twitter page which lists a maximum of 50 "tweets" of a user.
I have a List defined like this:
List<Tweet> tweets = new ArrayList<Tweet>(MAX_TWEETS);
Where Tweet
is a custom object type holding twitter update information(text, date, username, etc) and MAX_TWEETS
is a constant integer value(50).
Questions:
What is the benefit of setting the initial capacity of this List
, if any?
Should I bother setting a capacity when i know my list will be this small? When should i/should i not be setting a capacity?
The java. util. ArrayList. size() method returns the number of elements in this list i.e the size of the list.
Whenever an instance of ArrayList in Java is created then by default the capacity of Arraylist is 10. Since ArrayList is a growable array, it automatically resizes itself whenever a number of elements in ArrayList grow beyond a threshold.
size() method returns the size of the list as integer value. Integer max value is 2^31 and this value is equal to the 2147483647.
Default capacity of ArrayList is 10. once the max size is reached,new capacity will be: new capacity=(currentcapacity*3/2)+1. Show activity on this post.
Setting the initial capacity can increase the performance when populating the List, and it can also reduce the memory footprint of the List if you never add more than that number of items to the list.
The memory footprint of a List that has grown, and might have a backing array that is larger than the number of items stored can be reduced by invoking trimToSize()
By default, in Java 6, the size of a List is 10. That is, the system creates ten memory slots in the underlying Array. If you try adding the 11th element, only the Array copy is created. Providing a size improves performance.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With