Sort Objects in a ArrayList using Java Comparable Interface

In my previous tut you would have learnt how to sort objects in a ArrayList using java comparator. It is almost the same as the previous instead of a seperate class for the implementing the Comparator we can implement it in the same Employee Class and we have to override compareTo method instead of compare method. So let see how to sort objects based on the Comparable interface.

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class SortObj {
	public static void main(String args[]) {
		List l = new ArrayList();
		l.add(new Employee(20, "javainterviewpoint"));
		l.add(new Employee(10, "javainterview"));
		l.add(new Employee(30, "jip"));

		Collections.sort(l);
		System.out.println(l);
	}
}

class Employee implements Comparable {
	private String empname;
	private int eid;

	public Employee(int eid, String empname) {
		this.eid = eid;
		this.empname = empname;
	}

	public String getEmpname() {
		return empname;
	}

	public void setEmpname(String empname) {
		this.empname = empname;
	}

	public int getEid() {
		return eid;
	}

	public void setEid(int eid) {
		this.eid = eid;
	}

	public int compareTo(Employee e1) {
		// if this.eid is greater than e1's eid then it returns a positive
		// interger
		// if this.eid is lesser than e1's eid then it returns a negative
		// interger
		// if this.eid is equal than e1's eid then it returns zero
		return (this.getEid() - e1.getEid());
	}

	public String toString() {
		return " \n id : " + this.eid + " empname : " + this.empname;
	}
}

This will fetch you the ascendingly sorted Employee Objects.

[ id : 10 empname : javainterview,
id : 20 empname : javainterviewpoint,
id : 30 empname : jip]

If you want the sorted list to be in descending order then just reverse the condition in the compareTo method from return (this.getEid() – e1.getEid()) to return (e1.getEid() – this.getEid()).

Leave a Reply

Your email address will not be published. Required fields are marked *