Why Comparable and Comparator are useful?

In Java, Comparable and Comparator interfaces are useful for sorting the collection of objects. Java has some methods that are useful for sorting primitive types array or Wrapper classes array or list. So, first of all, we will see how we can sort our Primitive data type array and wrapper class array:

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class SortingOfDifferentObjects
	public static void main(String[] args) 
		// int array i.e Primitive data types
		int[] intArray = {2,9,11,1};
		// String array i.e Wrapper class
		String stringArray[] = {"BB", "DD", "RR", "LL"};	
		// Integer array i.e Wrapper class
		Integer integerArray[] = {3,8,10,2};
		// ArrayList containing wrapper class String
		List<String> listOfString = new ArrayList<String>();
		// Sorting of int array i.e Primitive data types
		// Sorting of String array i.e Wrapper class
		// Sorting of Integer array i.e Wrapper class
		// Sorting of ArrayList containing wrapper class String

Output: [1, 2, 9, 11]
[BB, DD, LL, RR]
[2, 3, 8, 10]
[A, B, E, L]

In the above example, you can see how we are sorting the Array of different types. To provide the Sorting functionality for Custom classes Java provides two interfaces
Java.lang.Comparable and java.util.Comparator 

comparable and comparator

Let’s take an example, suppose you are maintaining the data of the College. There is the number of Students and you want to collect all the data in ascending order of rollNo. So now you need to Sort them. But you can achieve this task by using a comparable and comparator interface. You can see the Sorting of custom classes in detail.

Leave a Comment

Follow us on Instagram & watch the latest videos on YouTube. Click below social icons to visit our Instagram & YouTube profiles.