确保java中对象的顺序

时间:2011-03-04 00:23:12

标签: java

我有一个看起来像这样的课程

class Student {
   public String str;   
   public int    marks;
}

说3个对象

学生S1(str:sub1,mark:10),S2(str:sub2,marks:5),S3(str:s3,marks:2)

我想确保对于Student对象,如果sub1>这个条件成立。 sub2> sub3 then marks1> marks2> marks3

1 个答案:

答案 0 :(得分:5)

让该类实现可比性:

class Student implements Comprable<Student> { 
....
    public int compareTo( Student other ) { 
        return this.marks - other.marks;
    }
 ...
}

这是一个有效的演示。在此演示中,您的类的自然顺序是“基于标记属性降序”。也就是说,更高的标记将放在较低的标记之前。

import java.util.*;
class Student implements Comparable<Student> {
   public String str;   
   public int  marks;

   public Student( String s, int m ) { 
     this.str = s;
     this.marks = m;
   }
   public int compareTo( Student other ) { 
    return other.marks - this.marks;
   }
   public String toString() { 
     return String.format("Student(str=%s,marks=%s)", str, marks);
   }

}
class Main { 
  public static void main( String ... args ) { 
    List<Student> l;
    Collections.sort(( l =  new ArrayList<Student>(Arrays.asList(
      new Student("sub3", 2),
      new Student("sub1", 10),
      new Student("sub2", 5)
    ))));
    System.out.println( l );
  }
}


C:\>java Main
[Student(str=sub1,marks=10), Student(str=sub2,marks=5), Student(str=sub3,marks=2)]