Search code examples
javaandroidcapacity

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?


Solution

  • Default capacity of ArrayList is set to 10 (see jdk 1.6 source). That means array of size 10 will be allocated on creation. If you will be adding element number 11 the capacity will increase to 16. Then increase again once you reach 21.

    If you don't expect more than 50 elements the array will resize at most 3 times. Given that small number, it really does not matter much. Set it to 50 if it gives you a piece of mind of saving on array copy.

    Actually this is correct formula of size increase:

    int newCapacity = (oldCapacity * 3)/2 + 1;