在实现Comparable接口的类中调用collections.sort()方法时引用的当前对象是什么?

时间:2016-08-23 05:23:40

标签: java sorting collections comparable

public class TestSort3{  
    public static void main(String args[]){  
        ArrayList<Student> al=new ArrayList<Student>();  
        al.add(new Student(101,"Vijay",23));  
        al.add(new Student(106,"Ajay",27));  
        al.add(new Student(105,"Jai",21));  

        Collections.sort(al);  
        for(Student st:al){  
            System.out.println(st.rollno+" "+st.name+" "+st.age);  
        }  
    }  
}  

compareTo的定义陈述为:

class Student implements Comparable <Student> {
    int rollno;
    String name;
    int age;
    Student(int rollno, String name, int age) {
        this.rollno = rollno;
        this.name = name;
        this.age = age;
    }

    public int compareTo(Student st) {
        if (age == st.age)
            return 0;
        else if (age > st.age)
            return 1;
        else
            return -1;
    }
}

我无法获得在compareTo方法中比较年龄的逻辑。调用Collections.sort()方法时,将调用compareTo()并且我们已经传递了ArrayList的实例,因此传递了Student类的实例,现在这是与之比较的其他Student实例?

我已经浏览了与此方法相关的其他stackoverflow链接,但我无法澄清我的疑问,请澄清一下。

2 个答案:

答案 0 :(得分:2)

  • 每个学生对象将与其他学生对象进行比较 你的清单。
  • 因此,当将一个学生对象年龄与在compareTo方法中作为参数传递的其他学生对象年龄进行比较时。

我们说我们有三名学生如下。

Student vijay = new Student(101, "vijay", 23);
Student ajay= new Student(106, "Ajay", 27); 
Student jai= new Student(105, "jai", 21);
  • 您有一名学生vijay,即new Student(101,"Vijay",23)
  • compareTo()中调用了
  • vijay方法,它将与ajay定义的new Student(106,"Ajay", 26 )进行比较。
  • compareTo()方法的实施方式是age将被比较,vijay在逻辑上会小于Ajay
  • 返回0表示对象在逻辑上相等
  • 返回负整数意味着this对象小于传递给compareTo方法的对象。
  • 返回正整数意味着this对象在逻辑上大于传递给compareTo()方法的对象。

总的来说,   - vijay将与ajay进行比较,由于我们的实施,vijay在逻辑上小于ajay。   - ajay将与jai进行比较,ajay将在逻辑上大于jai

对于具有所有组合的元素,此类过程将会发生,最终结果将按年龄递增,即jai < vijay < ajay

在java中实现了不同的排序算法,将根据与我们的问题无关的特定场景进行选择。

答案 1 :(得分:2)

this只是引用compareTo被调用的对象。如果调用Collections.sort可能是该集合的任何成员。

使其不那么抽象:

为了使用compareTo,必须像这样调用它:

a.comparTo(b)

其中ab都是Student的实例。 Collections.sort完全相同(虽然实际调用似乎在[Arrays.mergSort][1])。实例使用的细节取决于实现的排序算法和集合中元素的初始顺序。