Wednesday, April 24, 2019

Comparable In Java


Comparable Interface In Java.
  • Java Comparable is an interface.
  • It is defined in java.lang package. 
  • Used to sort list of objects or an array of object based on their natural order by implementing (Override) it’s compareTo() method in the objects.
  • Implementation should be like this. Method should return -1, 0, and 1 with comparison of "this" object and object we are passing as arguments.
  • All the Java API and wrapper class implements Comparable interface like List, array.
  • If any class implement Comparable interface in Java then collection of that object either List or Array can be sorted automatically by using  Collections.sort() or Arrays.sort() method and object will be sorted based on their natural order defined by CompareTo method.
Comparable interface defined in java API like below.
Comparable.java

public interface Comparable<T>
{
    public int compareTo(T o);
}

Comparable interface, we can sort the elements of:
  • String objects
  • Wrapper class objects, for example Integer, Long etc
  • User defined custom objects
  • All Java collection API.
Collections.sort() Vs.  Arrays.sort()
  • Collections.sort() : Use to sort a list of objects.
  • Arrays.sort() : Use sort an array of objects.
Example :
 
 ArrayList<String> list = new ArrayList<>(); 
 list.add("Kishan");
 list.add("Manoj");
 list.add("Sumati");
 list.add("Raju");
 list.add("Amit");

 //Sort Natural order
 Collections.sort(list);
 System.out.println(list);

 //Sort in reverse natural order
 Collections.sort(list, Collections.reverseOrder());
 System.out.println(list);
What is Collections.reverseOrder() ?

This is used to sort collections or array in the reverse-natural-order. Which implement the Comparable interface.

Example:  Sort custom user define class to sort and reverse order sorting.

User.java 

package com.javaiq.in.comparable;
public class User implements Comparable<User> { int id; String name; String role; public User(int id,String name,String role){ this.id=id; this.name=name; this.role = role; } public int getId() { return this.id; } public String getName() { return this.name; } public String getRole() { return this.role; } @Override public int compareTo(User o) { if (this.getId() > o.getId()) return 1; if (this.getId() < o.getId()) return -1;      else return 0; } @Override public String toString() { return this.id + ", " + this.name + ", " + this.role; } }
Sorting Calss Object Using Array.
MainClass.java

package com.javaiq.in.comparable;
import java.util.Arrays;
import java.util.Collections;
public class MainClass {
public static void main(String[] args) {
//User user[] = new User[4];
// Or
User[] user = new User[4];
user[0] = new User(1, "Rajeev", "Admin");
user[1] = new User(3, "Sumit", "User");
user[2] = new User(2, "Dinesh", "User");
user[3] = new User(4, "Kumar", "Admin");
System.out.println("#### Before Natural order ####");
System.out.println(Arrays.toString(user));
// Natural order
System.out.println("#### Sort Natural order ####");
Arrays.sort(user);
System.out.println(Arrays.toString(user));
// Sort in reverse natural order
System.out.println("#### Sort in reverse natural order ####");
Arrays.sort(user, Collections.reverseOrder());
System.out.println(Arrays.toString(user));
 }
}

Note:- If we not  implements Comparable<User>  interface it will give below Exception.

Exception in thread "main" java.lang.ClassCastException: com.javaiq.in.comparable.User cannot be cast to java.lang.Comparable
at java.util.ComparableTimSort.countRunAndMakeAscending(ComparableTimSort.java:320)
at java.util.ComparableTimSort.sort(ComparableTimSort.java:188)
at java.util.Arrays.sort(Arrays.java:1246)
at com.javaiq.in.comparable.MainClass.main(MainClass.java:22)

Sorting Calss Object Using List.
MainClassUsingList.java
      
package com.javaiq.in.comparable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class MainClassUsingList {
 public static void main(String[] args) {
  List<User> userList = new ArrayList<User>();
  userList.add(new User(1, "Rajeev", "Admin"));
  userList.add(new User(3, "Sumit", "User"));
  userList.add(new User(2, "Dinesh", "User"));
  userList.add(new User(4, "Kumar", "Admin"));
  System.out.println("#### Before Natural order ####");
  System.out.println(userList);
  // Natural order
  System.out.println("#### Sort Natural order ####");
  Collections.sort(userList);
  System.out.println(userList);
  // Sort in reverse natural order
  System.out.println("#### Sort in reverse natural order ####");>
  Collections.sort(userList, Collections.reverseOrder());
  System.out.println(userList);
 }
}

Note:- If we not  implements Comparable<User>  interface it will give below Exception.

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 


Bound mismatch: The generic method sort(List<T>) of type Collections is not applicable for the arguments (ArrayList<User>). The inferred type User is not a valid substitute for the bounded parameter <T extends Comparable<? super T>>

at com.javaiq.in.comparable.MainClassUsingList.main(MainClassUsingList.java:21)



No comments:

Post a Comment