2016-03-08 56 views
-2

的implimention問題基本上,我有2類。其中一個具有私有成員ArrayList(來自其他類的對象),並且列表中的每個對象都有一個私有字段點。我有一個方法遍歷列表並獲得所有點的總和。所以我只想比較list1> list2的總和點數。但我沒能做到這一點 - 我的compareTo()返回始終爲0與的compareTo()方法

這裏就是一個簡短的代碼示例。

public class StudentsGroup implements IFile, Comparable { 
    private List<Student> studentsList = new ArrayList<Student>(); 


    public int compareTo(Object o) { 
     if(StudentsGroup.getTotalPoints(studentsList) < ((StudentsGroup)o).getTotalPoints(studentsList)) 
      return 1; 
     else if(StudentsGroup.getTotalPoints(studentsList) > ((StudentsGroup)o).getTotalPoints(studentsList)) 
      return -1; 
     else 
      return 0; 
    } 

    public static int getTotalPoints(List<Student> studentsList1) { 
     int totalPoints = 0; 
     for(Student o : studentsList1) { 
      totalPoints += o.getStudentPoints(); 
     } 
     return totalPoints; 
    } 
} 

的方法

+0

你dedugged看你比較什麼?你是否真的在studentsList中有條目? – Stultuske

+0

@Stultuske,是的,我喜歡。我從.txt文件的構造函數中初始化它,並在列表中添加學生類的對象。我說,實際的方法是工作,當我打印出來的totalPoints,但問題是,list1.compareTo(列表2)總是返回0,彷彿列表總是由點相等,他們不是。 – meitriksx

回答

1
if(
    StudentsGroup.getTotalPoints(studentsList) < 
    ((StudentsGroup)o).getTotalPoints(studentsList)) 

你傳入同一個studentsList來計算的兩側。

的「另一組」 o完全不使用。

它可能看起來像o被使用,但getTotalPointsstatic方法,它並不重要,你叫什麼情況下它。編譯器也會給你一個警告。 不要忽略編譯器警告。

立即解決將是更改代碼以

if(getTotalPoints(studentsList) < getTotalPoints((StudentsGroup)o).studentsList) 

但你或許應該從public static改變getTotalPoints方法public(不是靜態)。而不是將該列表作爲參數傳遞,它可以在內部使用this.studentsList

if (this.getTotalPoints() < ((StudentsGroup)o).getTotalPoints()) 
+0

謝謝。我必須將方法設爲靜態,因爲程序是賦值的,所以我想我對靜態方法的調用是錯誤的。順便說一句,你需要在最後加1個大括號「(」後面的小符號和一個「)」來結束條件。 :) – meitriksx

1

在這種情況下,我會檢查該值是兩者不相同(或兩個0)

public class StudentsGroup implements IFile, Comparable<StudentsGroup> { 
    private List<Student> studentsList = new ArrayList<Student>(); 


    public int compareTo(StudentsGroup sg) { 
     return Integer.compare(getTotalPoints(), sg.getTotalPoints()); 
    } 

    public int getTotalPoints() { 
     return Math.toIntExact(studentsList.stream() 
              .mapToInt(Student::getStudentPoints).sum()); 
    } 
} 

通過簡化你不太可能混淆了一個靜態方法與實例方法的代碼(StudentsGroup)o).getTotalPoints(studentsList)只是調用StudentsGroup.getTotalPoints(studentsList),因爲您沒有實例方法。

+1

還要注意'Comparable <>'上適當的泛型類型不需要使用類型轉換。 – Thilo

+1

並且此代碼不會計算兩次的總和(原始代碼可能必須這樣做)。這也可以通過局部變量來實現。 – Thilo

+0

@Thilo我已經使用Math.toIntExact加入,而不是'(INT)') –