Replacement of a List element and Moving objects around in the list


In-place replacement of a List element

This example is about replacing a List element while ensuring that the replacement element is at the same position as the element that is replaced.

This can be done using these methods:

  • set(int index, T type)
  • int indexOf(T type)

Consider an ArrayList containing the elements "Program starting!", "Hello world!" and "Goodbye world!"

List<String> strings = new ArrayList<String>();
strings.add("Program starting!");
strings.add("Hello world!");
strings.add("Goodbye world!");

If we know the index of the element we want to replace, we can simply use set as follows:

strings.set(1, "Hi world");

If we don't know the index, we can search for it first. For example:

int pos = strings.indexOf("Goodbye world!");
if (pos >= 0)
{
   strings.set(pos, "Goodbye cruel world!");
}

Notes :

  • The set operation will not cause a ConcurrentModificationException.
  • The set operation is fast ( O(1) ) for ArrayList but slow ( O(N) ) for a LinkedList.
  • An indexOf search on an ArrayList or LinkedList is slow ( O(N) ).

Making a list unmodifiable

The Collections class provides a way to make a list unmodifiable:

List<String> ls = new ArrayList<String>();
List<String> unmodifiableList = Collections.unmodifiableList(ls);

If you want an unmodifiable list with one item you can use:

List<String> unmodifiableList = Collections.singletonList("Only string in the list");

Moving objects around in the list

The Collections class allows for you to move objects around in the list using various methods (ls is the List):

Reversing a list:

Collections.reverse(ls);

Rotating positions of elements in a list

The rotate method requires an integer argument. This is how many spots to move it along the line by. An example of this is below:

List<String> ls = new ArrayList<String>();
ls.add(" how");
ls.add(" are");
ls.add(" you?");
ls.add("hello,");
Collections.rotate(ls, 1);
for(String line : ls) System.out.print(line);
System.out.println();

This will print "hello, how are you?"

Shuffling elements around in a list

Using the same list above, we can shuffle the elements in a list:

Collections.shuffle(ls);

We can also give it a java.util.Random object that it uses to randomly place objects in spots:

Random random = new Random(12);
Collections.shuffle(ls, random);

Basic Programs