The List API has eight methods for positional access operations:
add(T type)
add(int index, T type)
remove(Object o)
remove(int index)
get(int index)
set(int index, E element)
int indexOf(Object o)
int lastIndexOf(Object o)
So, if we have a List:
List<String> strings = new ArrayList<String>();
And we wanted to add the strings "Hello world!" and "Goodbye world!" to it, we would do it as such:
strings.add("Hello world!");
strings.add("Goodbye world!");
And our list would contain the two elements. Now lets say we wanted to add "Program starting!" at the front of the list. We would do this like this:
strings.add(0, "Program starting!");
NOTE: The first element is 0.
Now, if we wanted to remove the "Goodbye world!" line, we could do it like this:
strings.remove("Goodbye world!");
And if we wanted to remove the first line (which in this case would be "Program starting!", we could do it like this:
strings.remove(0);
Note:
Adding and removing list elements modify the list, and this can lead to a ConcurrentModificationException
if the list is being iterated concurrently.
Adding and removing elements can be O(1)
or O(N)
depending on the list class, the method used, and whether you are adding / removing an element at the start, the end, or in the middle of the list.
In order to retrieve an element of the list at a specified position you can use the E get(int index);
method of the List API. For example:
strings.get(0);
will return the first element of the list.
You can replace any element at a specified position by using the set(int index, E element);
. For example:
strings.set(0,"This is a replacement");
This will set the String "This is a replacement" as the first element of the list.
Note: The set method will overwrite the element at the position 0. It will not add the new String at the position 0 and push the old one to the position 1.
The int indexOf(Object o);
returns the position of the first occurrence of the object passed as argument. If there are no occurrences of the object in the list then the -1 value is returned. In continuation of the previous example if you call:
strings.indexOf("This is a replacement")
the 0 is expected to be returned as we set the String "This is a replacement" in the position 0 of our list.
In case where there are more than one occurrence in the list when int indexOf(Object o);
is called then as mentioned the index of the first occurrence will be returned. By calling the int lastIndexOf(Object o)
you can retrieve the index of the last occurrence in the list. So if we add another "This is a replacement":
strings.add("This is a replacement");
strings.lastIndexOf("This is a replacement");
This time the 1 will be returned and not the 0;