1

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

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

4

1 回答 1

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
于 2020-01-17T09:50:34.777 回答