객체

2011-03-04 4 views
0

에 대한 자바 순서를 보장 I이객체

학생 S1이

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

말 3 개 물체처럼 보이는 클래스 (캐릭터 : SUB1, 마크 : 10), S2 (STR : SUB2, 마크 : 5), S3 (STR : S3, 마크 : 2)

나는 학생에 대한 즉,이 조건이 SUB1> SUB2> SUB3 다음 marks1> marks2> marks3

답변

5

가있는 경우 사실이 보유하고 있음을 개체를 확인하려면 비교를 구현하는 클래스 :

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)] 
+0

나는 또한 SUB1을 확인해야합니다> SUB2> SUB3뿐만 아니라 marks1> marks2> marks3 – kal

+0

That'a으로는 무엇을. 자세한 내용은 다음을 참조하십시오. http://download.oracle.com/javase/6/docs/api/java/lang/Comparable.html – OscarRyz

+0

이 경우에는 문제가되지 않지만 감산을 사용하여 구현할 때는주의하십시오. compareTo 메소드 언더 플로가 발생하면 파국적입니다. 가장 사소한 응용 프로그램에서만 사용해야합니다. (참고 - 이것이 내 대답을 확실히 얻었 기 때문에 큰 대답이 아님을 의미하지는 마십시오.) – corsiKa