6

what is the difference between the following declarations:

List list1 = new ArrayList();

List list2 = new ArrayList(10);

By default is allocates it with 10. But is there any difference? Can I add an 11th element to list2 by list2.add("something")?

1
  • 1
    You can add an 11th element, but only after you add the first 10.
    – ajb
    Aug 10, 2016 at 6:19

6 Answers 6

6

Here is the source code for you for first example

public  ArrayList() {
    this(10);
 }

So there is no difference. Since the initial capacity is 10, no matter you pass 10 or not, it gets initialised with capacity 10.

Can I add 11th element in the list2 by list2.add("something")?

Ofcourse, initial capacity is not final capacity. So as you keep on adding more than 10, the size of the list keeps increasing.

If you want to have a fixed size container, use Arrays.asList (or, for primitive arrays, the asList methods in Guava) and also consider java.util.Collections.unmodifiableList()

Worth reading about this change in Java 8 : In Java 8, why is the default capacity of ArrayList now zero?

In short, providing initial capacity wont really change anything interms of size.

7
  • 2
    Note the source code you're linking to is from JDK 6. Newer JDKs act quite differently - see, e.g., my answer above.
    – Mureinik
    Aug 10, 2016 at 6:06
  • So, what happens if size() is called on both the lists?
    – v0ld3m0rt
    Aug 10, 2016 at 6:06
  • 1
    10 element are null, so size is zero. Aug 10, 2016 at 6:07
  • 2
    @v0ld3m0rt Size is not capacity. Capacity is 10 and size is still zero as you not added anything to it. Aug 10, 2016 at 6:07
  • @v0ld3m0rt as size() just returns a variable size, which is only changed after modifing the List, it will be 0 Aug 10, 2016 at 6:10
4

You can always add elements in a list. However, the inlying array, which is used by the ArrayList, is initialized with either the default size of 10 or the size, which you specify when initializing the ArrayList. This means, if you e.g. add the 11th element, the array size has to be increased, which is done by copying the contents of the array to a new, bigger array instance. This of course needs time depending on the size of the list/array. So if you already know, that your list will hold thousands of elements, it is faster if you already initialize the list with that approximate size.

4

ArrayLists in Java are auto-growable, and will resize themselves if they need to in order to add additional elements. The size parameter in the constructor is just used for the initial size of the internal array, and is a sort of optimization for when you know exactly what you're going to use the array for.

Specifying this initial capacity is often a premature optimization, but if you really need an ArrayList of 10 elements, you should specify it explicitly, not assume that the default size is 10. Although this really used to be the default behavior (up to JDK 7, IIRC), you should not rely on it - JDK 8 (checked with java-1.8.0-openjdk-1.8.0.101-1.b14.fc24.x86_64 I have installed) creates empty ArrayLists by default.

2

The other answers have explained really well, but just to keep things relevant, in JDK 1.7.0_95:

/**
 * Constructs a new {@code ArrayList} instance with zero initial capacity.
 */
public ArrayList() {
    array = EmptyArray.OBJECT;
}


/**
 * Constructs a new instance of {@code ArrayList} with the specified
 * initial capacity.
 *
 * @param capacity
 *            the initial capacity of this {@code ArrayList}.
 */
public ArrayList(int capacity) {
    if (capacity < 0) {
        throw new IllegalArgumentException("capacity < 0: " + capacity);
    }
    array = (capacity == 0 ? EmptyArray.OBJECT : new Object[capacity]);
}

As the comment mentions, the constructor accepting no arguments initializes an ArrayList with zero initial capacity.

And even more interesting here is a variable (with a comment) that lends a lot of information on its own:

/**
 * The minimum amount by which the capacity of an ArrayList will increase.
 * This tuning parameter controls a time-space tradeoff. This value (12)
 * gives empirically good results and is arguably consistent with the
 * RI's specified default initial capacity of 10: instead of 10, we start
 * with 0 (sans allocation) and jump to 12.
 */
private static final int MIN_CAPACITY_INCREMENT = 12;
1
  • It's clear that Java devs in 1.7 have done some changes about this behaviour because in some javadoc they refer to the old initial capacity of 10. But the code tell us something different. Good post.
    – Aris2World
    Aug 10, 2016 at 6:56
1

You just picked the perfect example. Both actually do the same as new ArrayList() calls this(10) ;) But internally it would define the holding array with the size 10. the ArrayList#size method on the other side does just return a variable size, which only will be changed after adding and removing elements. This variable is also the main reason for IOOB Exceptions. So you wont be able to do so.

If you check the code of the ArrayList for example, you´ll notice that the method ArrayList#add will call ArrayList#rangeCheck. The range check actually just cares for the size variable and not the actuall length of the array holding the data for the List.

Due to this you´ll still not be able to insert data at the index 5 for example. The internal length of the data array at this point will be 10, but as you didn´t add anything to your List, the size variable will still be 0 and you´ll get the proper IndexOutOfBoundsException when you´ll try to do so.

just try to call list.size() after initializing the List with any size, and you´ll notice the returned size will be 0.

0

The initialization of ArrayList has been optimized since JDK 1.7 update 40 and there's a good explanation about the two different behaviours at this link java-optimization-empty-arraylist-and-Hashmap-cost-less-memory-jdk-17040-update.

So before Java 1.7u40 there're no difference but from that version there's a quite substantial difference.

This difference is about perfomance optimization and doesn't change the contract of List.add(E e) and ArrayList(int initialCapacity).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.