Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sorting objects in java

Tags:

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.

like image 807
user93796 Avatar asked Dec 13 '25 20:12

user93796


1 Answers

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)

like image 142
mats Avatar answered Dec 15 '25 09:12

mats



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!