Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaring the capacity of a List in Java

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?

like image 212
james Avatar asked May 25 '11 18:05

james


People also ask

How do you declare a list size in Java?

The java. util. ArrayList. size() method returns the number of elements in this list i.e the size of the list.

What is the capacity of list in Java?

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.

How do I limit the size of a list in Java?

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.

How do you find the capacity of a list?

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.


2 Answers

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()

like image 99
Kaj Avatar answered Sep 21 '22 08:09

Kaj


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.

like image 36
Sid Avatar answered Sep 23 '22 08:09

Sid