Positional Access Operations and Iterating over elements in a list


Positional Access Operations

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;


Iterating over elements in a list

For the example, lets say that we have a List of type String that contains four elements: "hello, ", "how ", "are ", "you?"

The best way to iterate over each element is by using a for-each loop:

public void printEachElement(List<String> list){
   for(String s : list){
      System.out.println(s);
   }
}

Output:

hello,
how
are
you?

To print them all in the same line, you can use a StringBuilder:

public void printAsLine(List<String> list){
   StringBuilder builder = new StringBuilder();
   for(String s : list){
      builder.append(s);
   }
   System.out.println(builder.toString());
}
 

Output:

hello, how are you?

Alternatively, you can use element indexing ( as described in Accessing element at ith Index from ArrayList ) to iterate a list. Warning: this approach is inefficient for linked lists.


Removing elements from list B that are present in the list A

Lets suppose you have 2 Lists A and B, and you want to remove from B all the elements that you have in A the method in this case is

List.removeAll(Collection c);

Example:

public static void main(String[] args)
{
    List<Integer> setX = new ArrayList<>();
    List<Integer> setY = new ArrayList<>();
    setX.addAll(Arrays.asList(new Integer[] { 2, 4, 5, 7, 8 }));
    setY.addAll(Arrays.asList(new Integer[] { 10, 11, 12, 4, 5, 8 }));
    System.out.println("X: " + setX);
    System.out.println("Y: " + setY);
    setY.removeAll(setX);
    System.out.println("Y after removal of common elements with X: " + setY);
}

Output:

X: [2, 4, 5, 7, 8]
Y: [10, 11, 12, 4, 5, 8]
Y after removal of common elements with X: [10, 11, 12]

Basic Programs