24

According to the docs you can insert objects an any position in a List:

The user of this interface has precise control over where in the list each element is inserted.

(source: http://download.oracle.com/javase/6/docs/api/java/util/List.html)

But the following program fails with an IndexOutOfBoundsException:

import java.util.ArrayList;

public class Test {
    public static void main(String[] args) {
        ArrayList<String> myList = new ArrayList<String>();
        myList.add(0, "derp");
        myList.add(2, "herp");

        for (String s : myList) {
            System.out.println("Le string: " + s);
        }
    }
}

It doesn't help setting initial capacity explicitly, either (which makes some sense since the default value is 10).

Why can't I insert objects at any position as long as its index is lower than the capacity? Is the size always equal to the number of inserted elements?

fiskeben
  • 3,395
  • 4
  • 31
  • 35

6 Answers6

31

You can insert an object at any valid position. Take a close look at the Javadoc for add(int, E):

Throws:
IndexOutOfBoundsException - if the index is out of range (index < 0 || index > size())

In other words, inserting an element always increases the size of the list by 1. You can insert at either end, or in the middle... but you can't insert past the end.

The capacity of an ArrayList is effectively an implementation detail - it controls when the backing array needs to be replaced by a larger one to cope with more elements. The size of a list is the important part here - a list with capacity 100 but size 5 is still only a list of 5 elements, and so inserting at position 67 into such a list would make no sense.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • 7
    @fiskeben: It's not lame - if you want an arbitrary key/value map, use `Map` instead. If you want to have an ordered list, you need to explicitly populate all the elements, not just randomly inject them with no notion of the real size of the list. – Jon Skeet Oct 21 '11 at 09:52
2

List capacity is not the same as its size.

The capacity is a property of array backed lists (such ArrayList or Vector), and it is the allocated size of the backing array (that is, the maximum number of items that you could put before needing to grow the structure).

The size, as you say, is the number of elements present in the list.

Then, why wouldn't you be able to insert an element wherever you want as long as there is space for it? Simple, because the List interface does not specify how the object is backed, and you couldn't do it in something like a LinkedList; so the homogeneous (and correct) behaviour is to throw an exception when that happens.

So you have two options:

  • Initialize the list properly by adding a default values up to your desired size.
  • If null is a sensible default value for you, you can use an array directly.
fortran
  • 74,053
  • 25
  • 135
  • 175
2

myList.add(2, "herp") should be myList.add(1, "herp")

As increases the size of List is by 1,not 2.

Yuhua Liu
  • 31
  • 1
0

ArrayList has two members: capacity and size

capacity is the length of the underlying array, size is the length of the array the ArrayList represents

so you have to add data in the list, so that the ArrayList itself gains the size where you want to insert data

Hachi
  • 3,237
  • 1
  • 21
  • 29
0

The size of the list is Always equal to the number of the inserted elements

Throws:
IndexOutOfBoundsException - if the index is out of range (index < 0 || index > size())

javadoc

pbanfi
  • 1,885
  • 2
  • 19
  • 23
0

First myList.add(0, "herp") will be inserted then it will check for size. Then, size is 1 but you are inserting at position 2.

lsoliveira
  • 4,560
  • 3
  • 20
  • 31