user93796 user93796 - 2 years ago 85
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 Source

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:,%20T)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download