Suresh Rohan's Blog

This blog is all about Java, J2EE,Spring, Angular, React JS, NoSQL, Microservices, DevOps, BigData, Tutorials, Tips, Best practice, Interview questions, Views, News, Articles, Techniques, Code Samples, Reference Application and much more

Thursday, October 29, 2015

Comparable and Comparator Interfaces In Java


Comparable and Comparator interfaces are used to compare similar objects

The Comparable class has only one method compareTo(), which is declared as follows:

int compareTo(Element that)
Since you are implementing the compareTo() method in a class, you have this reference available. You can compare the current element with the passed Element and return an int value.

Well, here are the rules for returning the integer value:

return 1 if current object > passed object
return 0 if current object == passed object
return -1 if current object < passed object

The comparison should mean natural ordering. For example, you saw how Integers are compared with each other, based on a numeric order, 

you compare Strings using lexicographic comparison, which is the natural order for Strings.


For user-defined classes, you need to find the natural order in which you can compare the objects. For example, for a Student class, StudentId might be the natural order for comparing Student objects.

ComparableTest.java
package com.appfworks.collections.comparable;

/**
* Created by suresh on 29/10/15.
*/
// This program shows the usage of Comparable interface

import java.util.*;

class Student implements Comparable {
String id;
String name;
Double cgpa;
public Student(String studentId, String studentName, double studentCGPA) {
id = studentId;
name = studentName;
cgpa = studentCGPA;
}
public String toString() {
return " \n " + id + " \t " + name + " \t " + cgpa;
}
public int compareTo(Student that) {
return this.id.compareTo(that.id);
}
}

public class ComparableTest {
public static void main(String []args) {
Student []students = { new Student("cs011", "Lennon ", 3.1),
new Student("cs021", "McCartney", 3.4),
new Student("cs012", "Harrison ", 2.7),
new Student("cs022", "Starr ", 3.7) };
System.out.println("Before sorting by student ID");
System.out.println("Student-ID \t Name \t CGPA (for 4.0) ");
System.out.println(Arrays.toString(students));
Arrays.sort(students);
System.out.println("After sorting by student ID");
System.out.println("Student-ID \t Name \t CGPA (for 4.0) ");
System.out.println(Arrays.toString(students));
}
}

You have implemented the Comparable<Student> interface. When you call the sort() method, it calls the compareTo() method to compare Student objects by their IDs. Since Student IDs are unique, it is a natural comparison order that works well.

ComparatorTest2.java
package com.appfworks.collections.comparator;

/**
* Created by suresh on 29/10/15.
*/
// This program shows the implementation of Comparator interface
import java.util.*;

class Student {
String id;
String name;
Double cgpa;
public Student(String studentId, String studentName, double studentCGPA) {
id = studentId;
name = studentName;
cgpa = studentCGPA;
}
public String toString() {
return " \n " + id + " \t " + name + " \t " + cgpa;
}
}

class CGPAComparator implements Comparator {
public int compare(Student s1, Student s2) {
return (s1.cgpa.compareTo(s2.cgpa));
}
}
public class ComparatorTest {
public static void main(String []args) {
Student []students = { new Student("cs011", "Lennon ", 3.1),
new Student("cs021", "McCartney", 3.4),
new Student("cs012", "Harrison ", 2.7),
new Student("cs022", "Starr ", 3.7) };
System.out.println("Before sorting by CGPA ");
System.out.println("Student-ID \t Name \t CGPA (for 4.0) ");
System.out.println(Arrays.toString(students));
Arrays.sort(students, new CGPAComparator());
System.out.println("After sorting by CGPA");
System.out.println("Student-ID \t Name \t CGPA (for 4.0) ");
System.out.println(Arrays.toString(students));
}
}

You create a separate class named CGPAComparator and implement the Comparator<Student> interface. You define the compare() method, which takes two Student objects as arguments.

it now uses the compare() method defined in the CGPAComparator. So, the Student objects are now compared and sorted based on their CGPA.



No comments:

Post a Comment