2016-03-08 64 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)') –