When you need some sort of ordering for the classes which you define, you will be going either for a comparable or comparator interface. Consider this example
package test;
import java.util.*;
public class TreeSetTest {
private static Set<Person> s = new TreeSet<Person>();
public static void main(String a[]){
s.add(new Person(20));
s.add(new Person(30));
s.add(new Person(10));
s.add(new Person(50));
System.out.println( s);
}
}
class Person implements Comparable<Person> {
int i;
Person(int i){
this.i = i;
}
public int compareTo(Person o) {
System.out.println(
int j = o.i;
System.out.println(
if (this.i < j) {
return -1;
} else if (this.i == j) {
return 0;
} else {
return 1;
}
}
public String toString() {
return String.valueOf(
}
}
Here in this case, the TreeSet API sorts the order of the Objects when you add to it. So, taking this example, if you try to add the Person objects to the TreeSet, it will be comparing the existing object with the object that is inserted and the comparison of objects is done by casting the objects to the Comparable interface and by invoking the compareTo method and the return value of this method determines the position where the object will be placed. When you use a comparable interface, you can sort the Class (in this case, Person) only with the logic you have specified in the compareTo method. But if you want to do different types of sorting of the same instances, then you can use Comparators based on the different instance variables available in the Class which you want to sort. The java.util.Collectio
The Java Classes which implements the Comparable interfaces are the wrapper classes like Integer, String, Character, Double, Long, Float etc..
To explain about Comparator, consider the following example
package test;
import java.util.Collectio
import java.util.List;
import java.util.ArrayList
import java.util.Comparato
public class ComparatorExample {
/**
* @param args
*/
public static void main(String[
List<ComparatorExample.
ComparatorExample temp = new ComparatorExample(
personList.add(
personList.add(
personList.add(
System.out.println(
IntComparator comparator = new IntComparator(
Collections.
System.out.println(
Collections.
System.out.println(
}
class Person {
private int index;
private String name;
Person(int index, String name) {
this.index = index;
this.name = name;
}
public String toString() {
return ” Name :: ” + this.name + ” Index :: ” + this.index;
}
}
static class IntComparator implements Comparator<Person> {
public int compare(Person o1, Person o2) {
int i = o1.index;
int j = o2.index;
if (i < j) {
return -1;
} else if (i == j) {
return 0;
} else {
return 1;
}
}
}
static class StringComparator implements Comparator<Person> {
public int compare(Person o1, Person o2) {
String name1 = o1.name;
String name2 = o2.name;
return name1.compareTo(
}
}
}
In the above given class, the objects have been sorted both based on the index and the name.
For the other question which you asked,