在比较器中重新初始化变量

时间:2018-06-13 19:06:48

标签: variables compare comparator

class Student
{   int id;
    String name;
    double gpa;

//parameterised constructor

//getter methods for id,name,gpa

@Override
public String toString() {
    return "Name: "+name+" ID: "+id+" GPA: "+gpa; 
 }

}
class StudentID implements Comparator<Student>
{   static int i;
    int j;


@Override
public int compare(Student s1,Student s2)
{   
    ++i; ++j;
    System.out.println("i="i+" j="+j);
    if(s1.getID()>s2.getID())
    {   
        return 1;
    }else if(s1.getID()<s2.getID())
    {   
        return -1;
    }else
    {   
        return 0;
    }

}
public class Comparator1 {
public static void main(String[] args) {
    List<Student> sl=new ArrayList<>();
    sl.add(new Student(3,"Aaa", 8.5));
    sl.add(new Student(1,"Bbb", 8.4));
    sl.add(new Student(4,"Ccc", 8.9));
    sl.add(new Student(2,"Ddd", 8.6));
    Comparator<Student> sortId=new StudentID();
    StudentID si=new StudentID();

    Collections.sort(sl,sortId);
    System.out.println("\n\tSorted by ID");
    for(Student student:sl)
        System.out.println(student);

    System.out.println("\ni="+si.i+"\nj="+si.j);       
}

}

获得的输出

i = 1 j = 1

i = 2 j = 2

i = 3 j = 3

i = 4 j = 4

i = 5 j = 5

按ID排序

名称:Bbb ID:1 GPA:8.4

姓名:Ddd ID:2 GPA:8.6

姓名:Aaa ID:3 GPA:8.5

姓名:Ccc ID:4 GPA:8.9

I = 5

J = 0

这里我预计j = 5但是它是0.有人可以解释一下吗?

0 个答案:

没有答案