coderz.py

Keep Coding Keep Cheering!

Comparable Interface in Java

java thread class

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.

  • If the object type is a string, it is sorted lexicographically.
  • Else, If the object type is a wrapper class object, such as an integer or a list, the values are sorted.
  • If the object type is custom, such as a user-defined object, then it is sorted using the compareTo() method.

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.

Declaration:
public interface Comparable<T>
compareTo(Object obj) method:
public int compareTo(Object obj)
  • It compares the current object to the provided object.
  • If the current object is greater than the requested object, it returns a positive integer.
  • Furthermore, If the current object is less than the given object, a negative integer is returned.
  • If the current object is equal to the requested object, the value is zero.
Example: Sorting User-Defined Object

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)); 
    }  
}
  
Output:
2 Rabecca
1 Alan
3 Ron

After Sorting :

1 Alan
2 Rabecca
3 Ron

Note: also read about the Collections Class in Java

Follow Me

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

Leave a Comment

Your email address will not be published. Required fields are marked *

Advertisement