4

Below code grabbed from google io open source.

com.google.android.apps.iosched.util.Lists.java http://code.google.com/p/iosched/source/browse/android/src/com/google/android/apps/iosched/util/Lists.java

public static <E> ArrayList<E> newArrayList(E... elements) {
    int capacity = (elements.length * 110) / 100 + 5;
    ArrayList<E> list = new ArrayList<E>(capacity);
    Collections.addAll(list, elements);
    return list;
}

com.google.android.apps.iosched.util.Sets.java http://code.google.com/p/iosched/source/browse/android/src/com/google/android/apps/iosched/util/Sets.java

public static <E> HashSet<E> newHashSet(E... elements) {
    int capacity = elements.length * 4 / 3 + 1;
    HashSet<E> set = new HashSet<E>(capacity);
    Collections.addAll(set, elements);
    return set;
}

What is the capacity variable supposed to mean? Thanks in advance!

  • My question is why they use that weird equation to calculate capacity of each collections. int capacity = (elements.length * 110) / 100 + 5;, int capacity = elements.length * 4 / 3 + 1; – user1165390 Mar 23 '12 at 19:42

2 Answers2

2

Those collections internally use a fixed array to save the data. "capacity" is the initial number of elements the array can accommodate. When you add more elements than current capacity the internal array must be extended. This is a time consuming operation and the initial capacity tries to help in case you know how many elements will be added.

azertiti
  • 3,090
  • 14
  • 19
1

This is part of the ArrayList class. Setting the capacity upfront prevents large lists from having to incrementally increase their size as they are filled and instead will allocate the needed space at once.

http://docs.oracle.com/javase/1.4.2/docs/api/java/util/ArrayList.html

ian.shaun.thomas
  • 3,349
  • 23
  • 39