【问题标题】:Sort a collection of objects in Java with comparable interface使用可比较的接口对 Java 中的对象集合进行排序
【发布时间】:2013-11-13 01:47:42
【问题描述】:

是否可以对具有可比接口的对象集合进行排序,并且当您发现某些属性等于增量值时?

我需要保持一个按数字属性排序的集合,识别属性并增加相等的值而不丢失排序

【问题讨论】:

  • 你试过了吗?
  • 那你需要写一个比较器。
  • 这个问题的部分内容不清楚。您是否在询问修改集合中的项目是否会破坏集合排序?当然,如果修改发生在比较器用来创建订单的字段上。

标签: java sorting collections comparable


【解决方案1】:

基于问题中的有限描述,您可以尝试使用以下代码:

class Student implements Comparable < Student >
{
  int rollno;
  String name;
  int age;
  Student (int rollno, String name, int age)
  {
    this.rollno = rollno;
    this.name = name;
    this.age = age;
  }

  public int compareTo (Student st)
  {
    if (age == st.age)
      {
        st.age += 1;
        return -1;
      }

    else if (age > st.age)
      return 1;
    else
      return -1;
  }
}

当您使用以下代码运行此代码时,您将获得所需的输出:

执行代码:

public static void main (String[]args)
  {
    ArrayList < Student > al = new ArrayList < Student > ();
    al.add (new Student (101, "Vijay", 23));
    al.add (new Student (106, "Ajay", 23));
    al.add (new Student (105, "Jai", 21));

    Collections.sort (al);
    for (Student st:al)
      {
        System.out.println (st.rollno + " " + st.name + " " + st.age);
      }
  }

输出:

105 Jai 21
106 Ajay 23
101 Vijay 24

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-08-18
    • 2016-10-23
    • 2020-05-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多