가있는 경우 사실이 보유하고 있음을 개체를 확인하려면 비교를 구현하는 클래스 :
class Student implements Comprable<Student> {
....
public int compareTo(Student other) {
return this.marks - other.marks;
}
...
}
다음은 작동하는 데모입니다. 이 데모에서 클래스의 자연 순서는 "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)]
나는 또한 SUB1을 확인해야합니다> SUB2> SUB3뿐만 아니라 marks1> marks2> marks3 – kal
That'a으로는 무엇을. 자세한 내용은 다음을 참조하십시오. http://download.oracle.com/javase/6/docs/api/java/lang/Comparable.html – OscarRyz
이 경우에는 문제가되지 않지만 감산을 사용하여 구현할 때는주의하십시오. compareTo 메소드 언더 플로가 발생하면 파국적입니다. 가장 사소한 응용 프로그램에서만 사용해야합니다. (참고 - 이것이 내 대답을 확실히 얻었 기 때문에 큰 대답이 아님을 의미하지는 마십시오.) – corsiKa