使用类似的接口对Java中的对象集合进行排序

时间:2013-11-01 19:20:18

标签: java sorting collections

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

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

1 个答案:

答案 0 :(得分: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