2011-03-04 64 views
0

我有一個類,看起來像這樣確保爲了在Java中的對象

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

說3個

學生S1對象(STR:SUB1,痕跡:10),S2(STR:SUB2,標誌:5),S3(STR:S3,標記:2)

我希望確保爲學生對象,這種情況也是如此,如果SUB 1> SUB2> SUB3則標誌1> marks2> marks3

回答

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

我還需要確保sub1> sub2> sub3以及marks1> marks2> marks3 – kal 2011-03-04 00:35:09

+0

這就是它的功能。在這裏閱讀更多關於它的內容:http://download.oracle.com/javase/6/docs/api/java/lang/Comparable.html – OscarRyz 2011-03-04 00:37:33

+0

雖然在這種情況下可能不是問題,但在使用減法實施時要小心compareTo方法。發生下溢會是災難性的。它只能用在最瑣碎的應用程序中。 (注意 - 不要認爲這不是一個好的答案,因爲它肯定會得到我的讚賞。) – corsiKa 2011-03-04 01:00:14