在java中排序对象 [英] sorting objects in java

查看:114
本文介绍了在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.

推荐答案

例如,给出这个类(公共字段只是为了简洁):

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

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

您可以使用静态排序(List,Comparator)方法按时间实现排序在java.util.Collections类中。这里,创建了一个匿名内部类来实现作业的比较器。这有时被称为函数指针的替代(因为Java没有这些)。

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;
        }
    });
}

请注意compare()方法的合约模型: http://java.sun.com /javase/6/docs/api/java/util/Comparator.html#compare(T,%20T)

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

这篇关于在java中排序对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆