2014-02-16 29 views
1

我有一個類中有一個對象的列表。我需要根據列表對象的浮點值對列表進行排序,但在使用Array.sort方法後,下面的代碼不起作用,我打印出集合,但學生列表不會按照GPA排序。如何排序和保留web服務的結果?

學校類

public class School{ 

    private List<Student> students; 
    public School(){ 
    this.students = new ArrayList(); 
    } 
} 

Student類

public class Student implements Comparable<Student> { 

private int id; 
private float GPA; 
... 
public int compareTo(Student student) { 
     float compareGPA = student.getGPA(); 
     return (int)(this.getGPA() - compareGPA); 
} 

} 

代碼進行排序這是主要方法

Arrays.sort(this.school.getStudents().toArray()); 
+2

「不行」不是一個好問題描述。 – qqilihq

+0

@qqilihq謝謝我添加了更多細節 – J888

+1

重新讀取最後一行後,問題是:'#toArray'從列表中創建一個新數組。只有數組是排序的,而不是List本身(這就是你明顯想要的)。請參閱下面的@ donfoxx的答案,瞭解如何解決這個問題。 – qqilihq

回答

2

你可以排序是這樣的:

Collections.sort(this.school.getStudents()); 

,你應該在這裏指定<Student>還有:

this.students = new ArrayList<Student>(); 
1

的問題是要排序的中間結果 - 即不存儲陣列 - 和你沒有做任何事的。

什麼你基本上做的是現在:

Object[] intermediate = this.school.getStudents().toArray(); 
Arrays.sort(intermediate); 
//do nothing with intermediate 

該解決方案將使用Collections.sort()代替(更好) - 或存儲中間陣列,排序,然後將其恢復爲您students列表(更糟糕)

1

this.school.getStudents().toArray()創建一個臨時數組實例,並且Array.sort()對臨時數組進行排序,而不是您實際的ArrayList。您可以使用Collections.sort(this.school.getStudents());代替

0

您可以分別使用Collections.sort(this.school.getStudents());Collections.reverse(this.school.getStudents());作爲升序和降序。