user93796 user93796 - 6 months ago 8
Java Question

sorting objects in java

i want to do nested sorting . I have a course object which has a set of applications .Applications have attributes like time and priority. Now i want to sort them according to the priority first and within priority i want to sort them by time.

Answer

For example, given this class (public fields only for brevity):

public class Job {
    public int prio;
    public int timeElapsed;
}

you might implement sorting by time using the static sort(List, Comparator) method in the java.util.Collections class. Here, an anonymous inner class is created to implemented the Comparator for "Job". This is sometimes referred to as an alternative to function pointers (since Java does not have those).

public void sortByTime() {
	AbstractList<Job> list = new ArrayList<Job>();
	//add some items
	Collections.sort(list, new Comparator<Job>() {
		public int compare(Job j1, Job j2) {
			return j1.timeElapsed - j2.timeElapsed;
		}
	});
}

Mind the contract model of the compare() method: http://java.sun.com/javase/6/docs/api/java/util/Comparator.html#compare(T,%20T)