【问题标题】:what is the current object referred to while calling collections.sort() method inside a class which implements Comparable interface?在实现 Comparable 接口的类中调用 collections.sort() 方法时引用的当前对象是什么?
【发布时间】:2016-12-29 19:07:33
【问题描述】:
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 链接,但我无法澄清我的疑问,请澄清这一点。

【问题讨论】:

    标签: java sorting collections comparable


    【解决方案1】:
    • 每个学生对象都将与其他学生对象进行比较 你的清单。
    • 因此,当一个学生对象年龄将与作为参数传递给 compareTo 方法的其他学生对象年龄进行比较时。

    假设我们有以下三个学生。

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

    总体而言, - vijay 将与 ajay 进行比较,由于我们的实现,vijay 在逻辑上小于 ajay。 - ajay 将与 jai 进行比较,ajay 将在逻辑上大于 jai

    所有组合的元素都会发生这种过程,最终结果将按年龄递增的顺序排列,即jai &lt; vijay &lt; ajay

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

    【讨论】:

    • 所以这就像选择排序实现需要 O(n^2) 时间对吗?
    【解决方案2】:

    this 只是指调用compareTo 的对象。在调用 Collections.sort 的情况下,可能是集合的任何成员。

    为了不那么抽象:

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

    a.comparTo(b)
    

    其中ab 都是Student 的实例。 Collections.sort 正是这样做的(尽管实际调用似乎在 [Arrays.mergSort][1] 中)。使用哪个实例的详细信息取决于实现的排序算法和集合中元素的初始顺序。

    【讨论】:

      猜你喜欢
      • 2022-07-08
      • 2017-12-05
      • 1970-01-01
      • 2021-11-10
      • 2016-08-02
      • 2013-08-16
      • 2021-01-19
      • 2021-07-20
      • 2020-09-29
      相关资源
      最近更新 更多