Making a list unmodifiable

The list unmodifiable method is used to returns an unmodifiable view of the specified list. The Collections class provides a way to make a list unmodifiable:

List ls = new ArrayList();
List unmodifiableList = Collections.unmodifiableList(ls);

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

List 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 ls = new ArrayList();
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);

Creating, Adding and Removing element from an ArrayList

ArrayList is one of the inbuilt data structures in Java. It is a dynamic array (where the size of the data structure not needed to be declared first) for storing elements (Objects).

It extends AbstractList class and implements List interface. An ArrayList can contain duplicate elements where it maintains insertion order. It should be noted that the class ArrayList is non-synchronized, so care should be taken when handling concurrency with ArrayList. ArrayList allows random access because array works at the index basis. Manipulation is slow in ArrayList because of shifting that often occurs when an element is removed from the array list.

An ArrayList can be created as follows:

List myArrayList = new ArrayList<>();

Where T ( Generics ) is the type that will be stored inside ArrayList.

The type of the ArrayList can be any Object. The type can’t be a primitive type (use their wrapper classes instead).

To add an element to the ArrayList, use add() method:

myArrayList.add(element);

Or to add item to a certain index:

myArrayList.add(index, element); //index of the element should be an int (starting from 0)

To remove an item from the ArrayList, use the remove() method:

myArrayList.remove(element);

Or to remove an item from a certain index:

myArrayList.remove(index); //index of the element should be an int (starting from 0)

Creating a List

Giving your list a type

To create a list you need a type (any class, e.g. String). This is the type of your List. The List will only store objects of the specified type. For example:

List strings;

Can store “string1”, “hello world!”, “goodbye”, etc, but it can’t store 9.2, however:

List doubles;

Can store 9.2, but not “hello world!”.

Initialising your list

If you try to add something to the lists above you will get a NullPointerException, because strings and doubles both equal null!

Related Article: Lists in Java with Examples

There are two ways to initialise a list:

Option 1: Use a class that implements List

List is an interface, which means that does not have a constructor, rather methods that a class must override. ArrayList is the most commonly used List, though LinkedList is also common. So we initialise our list like this:

List strings = new ArrayList();
or
List strings = new LinkedList();
Version ≥ Java SE 7

Starting from Java SE 7, you can use a diamond operator:

List strings = new ArrayList<>();

or

List strings = new LinkedList<>();

Option 2: Use the Collections class

The Collections class provides two useful methods for creating Lists without a List variable:

  • emptyList(): returns an empty list.
  • singletonList(T): creates a list of type T and adds the element specified.

And a method which uses an existing List to fill data in:

  • addAll(L, T…): adds all the specified elements to the list passed as the first parameter.

Examples:

import java.util.List; import java.util.Collections; List l = Collections.emptyList(); List l1 =
Collections.singletonList(42); Collections.addAll(l1, 1, 2, 3);

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 strings = new ArrayList();

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 list){
    for(String s : list){
        System.out.println(s);
    }
}

Which would print:

hello,
how
are
you?

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

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

Will print:

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 numbersA = new ArrayList<>();
    List numbersB = new ArrayList<>();
    numbersA.addAll(Arrays.asList(new Integer[] { 1, 3, 4, 7, 5, 2 }));
    numbersB.addAll(Arrays.asList(new Integer[] { 13, 32, 533, 3, 4, 2 }));
    System.out.println("A: " + numbersA);
    System.out.println("B: " + numbersB);
    numbersB.removeAll(numbersA);
    System.out.println("B cleared: " + numbersB);
}

this will print

A: [1, 3, 4, 7, 5, 2]
B: [13, 32, 533, 3, 4, 2]
B cleared: [13, 32, 533]

Leave a Comment