What is the CopyOnWriteArrayList.sort method() in Java?

What is CopyOnWriteArrayList?

  • The CopyOnWriteArrayList method is a thread-safe implementation of ArrayList without the requirement for synchronization.
  • The whole content of the CopyOnWriteArrayList is duplicated into a new internal copy when we use any of the altering methods, such as add() or delete(). Hence, the list can be iterated in a safe way, without any fear of losing data, while modifying it simultaneously.
  • The data structure’s properties make it particularly helpful in situations when we iterate it more frequently than we alter it.
  • If adding items is a typical activity, CopyOnWriteArrayList isn’t the appropriate data structure to use as the extra copies will almost always result in poor performance.

What is the sort() method?

sort() is an instance method of the CopyOnWriteArrayList which is used to sort the given list. The method takes a Comparator as the parameter to compare the elements of the list. The sorting operation is in-place in nature, that is, the original list is modified.

The sort method is defined in the CopyOnWriteArrayList class. The CopyOnWriteArrayList class is defined in the java.util.concurrent package. To import the CopyOnWriteArrayList class, check the following import statement.

import java.util.concurrent.CopyOnWriteArrayList;

Syntax


public void sort(Comparator<? super E> c)

Parameters

  • Comparator<? super E> c: The Comparator to use for comparing the elements of the list.

Return value

This method doesn’t return anything.

Code

import java.util.Comparator;
import java.util.concurrent.CopyOnWriteArrayList;
public class Main {
public static void main(String[] args){
CopyOnWriteArrayList<String> copyOnWriteArrayListObject = new CopyOnWriteArrayList<>();
copyOnWriteArrayListObject.add("edpresso");
copyOnWriteArrayListObject.add("educative");
copyOnWriteArrayListObject.add("coding-interview");
copyOnWriteArrayListObject.add("courses");
System.out.println("List before sorting - " + copyOnWriteArrayListObject);
copyOnWriteArrayListObject.sort(Comparator.naturalOrder());
System.out.println("List after sorting - " + copyOnWriteArrayListObject);
}
}

Explanation

  • Lines 1-2: We import the relevant classes.
  • Line 7: We create an instance of the CopyOnWriteArrayList class called copyOnWriteArrayListObject.
  • Lines 9-12: We insert elements to copyOnWriteArrayListObject using the add() method.
  • Line 14: We print the contents of the list copyOnWriteArrayListObject before sorting.
  • Line 16: We invoke the sort() method on the list passing a natural order comparator.
  • Line 18: We print the contents of the list copyOnWriteArrayListObject after sorting.

Free Resources