Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert at any position in java.util.List

Tags:

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?

like image 394
fiskeben Avatar asked Oct 21 '11 09:10

fiskeben


People also ask

How do you add values to a list in Java?

There are two methods to add elements to the list. add(E e): appends the element at the end of the list. Since List supports Generics, the type of elements that can be added is determined when the list is created. add(int index, E element): inserts the element at the given index.

How do you insert an element at the beginning of the list Java?

The standard solution to insert a specified item at the specified position in the list is to use the add(index, element) method in the List interface, which takes the index and the element to be inserted.

How do you add an element to an ArrayList at a specific index?

The java. util. ArrayList. add(int index, E elemen) method inserts the specified element E at the specified position in this list.It shifts the element currently at that position (if any) and any subsequent elements to the right (will add one to their indices).


2 Answers

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.

like image 81
Jon Skeet Avatar answered Dec 17 '22 11:12

Jon Skeet


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.
like image 20
fortran Avatar answered Dec 17 '22 11:12

fortran