有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java您可以用两种不同的方式对这个ArrayList进行排序,编写自己的比较器吗?

我有一个名为Course的对象数组列表,我试图按courseID和courseStartTime两种方式对它进行排序

编辑:为了澄清我的意思,我想在某个时间点按courseID排序,然后在另一个时间点按courseStartTime排序

class Course implements Comparable<Course> {
    private int courseID;
    private String courseBeginTime;

    @Override
    public int compareTo(Course course) {
        //what to return?
    }

如果我编写了两个自己的比较器,一个用来比较courseID,另一个用来比较courseStarTime,那么类中的compareTo()方法就不用了,我不知道返回什么

如果我想使用compareTo()方法,我不确定如何编写它,以便比较courseIDcourseStartTime


共 (4) 个答案

  1. # 1 楼答案

    也许你应该这样做

    public class Course implements Comparator<Course> {
    
        private int compareTime(int lhsTime, int rhsTime) {
            if (lhsTime > rhsTime) {
                return 1;
            } else if (lhsTime == rhsTime) {
                return 0;
            } else {
                return -1;
            }
        }   
    
        @Override
        public int compare(Course lhs, Course rhs) {
            if (lhs.id > rhs.id) {
                return 1;
                  //Get the time object from course obj and pass to compaerTime
            } else if (lhs.courseStarTime == rhs.courseStarTime) {
                return compareTime(lhs, rhs);
            } else {
                return -1;
            }
        }
    
    }
    
  2. # 2 楼答案

    可以实现两个不同的比较器

    public class CourseComparatorById implements Comparator<Course> {
    
        @Override
        public int compare(Course o1, Course o2) {
            // for example - sort ascending by ID
            return o1.getId() - o2.getId();
        }
    }
    
    public class CourseComparatorByStartTime implements Comparator<Course> {
    
        @Override
        public int compare(Course o1, Course o2) {
            // for example - sort ascending by start time
            return o1.getStartTime() - o2.getStartTime();
        }
    }
    

    然后使用它们对数组进行排序

    List<Course> courses = ...
    
    Collections.sort(courses, new CourseComparatorById());
    // now it's sorted by ID
    
    Collections.sort(courses, new CourseComparatorByStartTime());
    // now it's sorted by start time
    
  3. # 3 楼答案

    我有一种感觉,这是被用于在线注册网络应用。。。 您可能正在从RDB获取数据源。。。将所有课程放在一个列表(一个实体)中并保存是不明智的。我会为每个课程创建一个对象(包含courseID和courseBeginTime),并将它们全部保存。然后在查询时,添加提示,根据实体中的任何根参数(如courseID或courseBeginTime)对实体进行排序,最后是一个列表,其中包含按所需方式排序的对象:):)

  4. # 4 楼答案

    您也可以尝试Java 8 Lambda方式:

    // this sorts by courseID
    courseList.sort((c1, c2) -> Integer.valueOf(c1.courseID).compareTo(c2.courseID));
    
    // this sorts by String courseBeginTime
    courseList.sort((c1, c2) -> c1.courseBeginTime.compareTo(c2.courseBeginTime));
    

    注意,在Java 8中,您不必使用Collections.sort,因为新的List接口还提供了sort方法