The Comparable interface is used to compare an object of the same class with an instance of that class; it also enables data ordering for user-defined class objects. The class has to implement the java.lang.Comparable interface to compare its instance, it provides the compareTo() method, which accepts an object of that class as an argument.
Its sorting algorithm is determined by the type of object used by the interface.
Collections.sort() can be used to sort classes that implement this interface automatically. Objects that implement this interface can be used as keys in a sorted map or as elements in a sorted set without requiring a comparator to be specified.
public interface Comparable<T>
public int compareTo(Object obj)
import java.util.*;
class Coderz implements Comparable <Coderz>
{
int Id;
String name;
public Coderz (int Id, String name)
{
this.Id=Id;
this.name=name;
}
public String toString()
{
return this.Id + " " + this.name;
}
// Sorting by Id
public int compareTo(Coderz std){
// we compare
return this.Id - std.Id;
}
}
public class Demo {
public static void main(String a[]){
ArrayList <Coderz> list = new ArrayList <Coderz> ( );
list.add(new Coderz(2, "Rabecca"));
list.add(new Coderz(1, "Alan"));
list.add(new Coderz(3, "Ron"));
// Displaying
for (int i=0; i<list.size(); i++)
System.out.println(list.get(i));
// Sorting
Collections.sort(list);
// Displaying after sorting
System.out.println("\nAfter Sorting :\n");
for (int i=0; i<list.size(); i++)
System.out.println(list.get(i));
}
}
2 Rabecca
1 Alan
3 Ron
After Sorting :
1 Alan
2 Rabecca
3 Ron
Note: also read about the Collections Class in Java
If you like my post, please follow me to read my latest post on programming and technology.
https://www.instagram.com/coderz.py/
https://www.facebook.com/coderz.py
Staying up to the mark is what defines me. Hi all! I’m Rabecca Fatima a keen learner, great enthusiast, ready to take new challenges as stepping stones towards flying colors.
Problem Statement: Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. Example…
Given an integer A. Compute and return the square root of A. If A is…
Given a zero-based permutation nums (0-indexed), build an array ans of the same length where…
A heap is a specialized tree-based data structure that satisfies the heap property. It is…
What is the Lowest Common Ancestor? In a tree, the lowest common ancestor (LCA) of…