Comparator Vs Comparable

Comparator

The actual compare function, can be used separately or with sorting. For example:

class PersonComparator implements Comparator<Person> {  
	@Override  
	public int compare(Person person1, Person person2) {  
		return person1.getAge() - person2.getAge();  
	}  
}
public static void main(String[] args) throws InterruptedException {
	List<Person> personList = Lists.newArrayList(
			new Person("Austin", 9),
			new Person("Bubu", 2),
			new Person("Cubu", 19),
			new Person("XiXi", 9)
	);

	personList.sort(new PersonComparator());
	System.out.println(personList);
}
[Bubu, Austin, XiXi, Cubu]

Comparable

With comparable, we can just make personList to works with sort() without the need of comparator.

So if our Person classes implements Comparable

class Person implements Comparable<Person> {
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public int getAge() {
        return age;
    }

    @Override
    public String toString() {
        return name;
    }

    @Override
    public int compareTo(Person other) {
        return this.age - other.age;
    }
}

We can just sort without Comparator

public static void main(String[] args) throws InterruptedException {
	List<Person> personList = Lists.newArrayList(
			new Person("Austin", 9),
			new Person("Bubu", 2),
			new Person("Cubu", 19),
			new Person("XiXi", 9)
	);

	Collections.sort(personList);
	System.out.println(personList);
}
[Bubu, Austin, XiXi, Cubu]