Created
July 19, 2014 19:02
-
-
Save afaquejam/797f6b05f3b68e149e82 to your computer and use it in GitHub Desktop.
Java Comparator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Comparable interface allows us to sort the objects according to the natural | |
// order. For example, you want to sort a bunch of strings. The natural order | |
// would be to sort them accroding to their Case sensitivity (Unicode). | |
// But what if you want to convey a message to the sort algorithm that you want | |
// to sort the strings in an case insensitive way. The way you do that is by using | |
// comparators. | |
// Alright, there are two entities here. | |
// An class which implements whose objects are to be compared. | |
// A sorting class that compares the comparable types. | |
// To implement a comparator interface to your class, you need to | |
// * Create a nested class that implements the comparator interface. | |
// * implement the compare method. | |
// * Create a static final Comparator object of the class that implements the | |
// comparable interface. | |
// The sorting algorithm class will take the comparator object and invoke the | |
// compare method on two comparable objects. | |
// MergeSort.sort(array, Student.BY_NAME); | |
// MergeSort.sort(array, Student.BY_SECTION); | |
import java.util.Comparator; | |
public class Student implements Comparable<Student> { | |
private String name; | |
private int section; | |
public static final Comparator<Student> BY_NAME = new ByName(); | |
public static final Comparator<Student> BY_SECTION = new BySection(); | |
public int compareTo(Student that) { | |
return 0; | |
} | |
private static class ByName implements Comparator<Student> { | |
public int compare(Student one, Student two) { | |
return one.compareTo(two); | |
} | |
} | |
private static class BySection implements Comparator<Student> { | |
public int compare(Student one, Student two) { | |
return one.section = two.section; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment