Wednesday, 27 September 2017

JAVA : Comparable vs Comparator

JAVA : Comparable vs Comparator

#########################  Shortcut rememberance  ################################################
Comparable - compareTo(o)  - API person or who develop the object will write, 
JVM will call internally when treeSet.add(o) does, 
Dont pass any thing in Constructor, so that JVM will call compareTo(o) method.
Comparator - compare(o1,o2) - equals() - Who uses API class or developed class will write
JVM will call internally when treeSet.add(o) does.
Pass MyComparator object in constructor, so that JVM will call compare(o1,o2) method.

#########################################################################




Comparable


- When default sorting is needed, means JVM will call automatically when we try to add objects to TreeSet, that is with default constructor.

- The person who develops the class is responsible to implement Comparable and write logic inside compareTo() method.
Eg: Person1 develops Employee class, so he is responsible to write compareTo().


Comparator


- When we want customized sorting based on our logic, then just pass MyComparator class in the constructor, so that JVM will not call compareTo method instead it calls our compare() method which is inside MyComparator class.

- need to pass MyComparator class in constructor - so that JVM will understand to call compare()

- The person who uses the class can write his own MyComparator and implement inside compare().
Eg : Person2 is using Employee class developed by Person1, so Person2 can write MyComparator and compare() to change the sorting order.







Comparable Example

public class Employee implements Comparable<Employee> {

    private int id;
    private String name;
    private int age;
    private long salary;

//getter and setter......

    @Override
    public int compareTo(Employee emp) {
        return (this.id - emp.id);
    }

}
In Main method 
Employee[] empArr = new Employee[4];                           empArr[0] = new Employee(10, "Mikey", 25, 10000);
empArr[1] = new Employee(20, "Arun", 29, 20000);
empArr[2] = new Employee(5, "Lisa", 35, 5000);
empArr[3] = new Employee(1, "Pankaj", 32, 50000);

//sorting employees array using Comparable interface implementation
Arrays.sort(empArr);

Comparator Example

class HDTV implements Comparator{
 private int size;
 private String brand;
 
 public HDTV(int size, String brand) {
  this.size = size;
  this.brand = brand;
 }
 
 public int getSize() {
  return size;
 }
 
 public void setSize(int size) {
  this.size = size;
 }
 
 public String getBrand() {
  return brand;
 }
 
 public void setBrand(String brand) {
  this.brand = brand;
 }
}

@Override
 public int compare(HDTV tv1, HDTV tv2) {
  int tv1Size = tv1.getSize();
  int tv2Size = tv2.getSize();
 
  if (tv1Size > tv2Size) {
   return 1;
  } else if (tv1Size < tv2Size) {
   return -1;
  } else {
   return 0;
  }
 }
In Main method  
                                                                  
HDTV tv1 = new HDTV(55, "Samsung");
  HDTV tv2 = new HDTV(60, "Sony");
  HDTV tv3 = new HDTV(42, "Panasonic");
 
  ArrayList<HDTV> al = new ArrayList<HDTV>();
  al.add(tv1);
  al.add(tv2);
  al.add(tv3);
Collection.sort(al, HDTV);
OR
public class Employee implements Comparator {

    private int id;
    private String name;
    private int age;
    private long salary;

/**
     * Comparator to sort employees list or array in order of Salary
     */
    public static Comparator<Employee> SalaryComparator = new Comparator<Employee>() {

        @Override
        public int compare(Employee e1, Employee e2) {
            return (int) (e1.getSalary() - e2.getSalary());
        }
    };
    /**
     * Comparator to sort employees list or array in order of Age
     */
    public static Comparator<Employee> AgeComparator = new Comparator<Employee>() {

        @Override
        public int compare(Employee e1, Employee e2) {
            return e1.getAge() - e2.getAge();
        }
    };
    /**
     * Comparator to sort employees list or array in order of Name
     */
    public static Comparator<Employee> NameComparator = new Comparator<Employee>() {

        @Override
        public int compare(Employee e1, Employee e2) {
            return e1.getName().compareTo(e2.getName());
        }
    };
}
In main method                                                      //sort employees array using Comparator by Salary Arrays.sort(empArr, Employee.SalaryComparator);
System.out.println("Employees list sorted by Salary:\n"+Arrays.toString(empArr));

//sort employees array using Comparator by Age
Arrays.sort(empArr, Employee.AgeComparator);
System.out.println("Employees list sorted by Age:\n"+Arrays.toString(empArr));

//sort employees array using Comparator by Name
Arrays.sort(empArr, Employee.NameComparator);
System.out.println("Employees list sorted by Name:\n"+Arrays.toString(empArr));
https://www.journaldev.com/780/comparable-and-comparator-in-java-example

No comments:

Post a Comment