java - 'compareTo' 比较用例

标签 java collections

package Comparable;

public class Movie implements Comparable<Movie> {

    private double rating;
    private String name;
    private int year;

    @Override
    public int compareTo(Movie m) {
        // TODO Auto-generated method stub
        return this.year - m.year;
    }

    public Movie(double rating, String name, int year) {
        this.rating = rating;
        this.name = name;
        this.year = year;
    }    
}

主类:

package Comparable;

import java.util.ArrayList;
import java.util.Collections;

public class Main {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        ArrayList<Movie> list = new ArrayList<Movie>();
        list.add(new Movie(8.8, "Force Awakens", 2015));
        list.add(new Movie(7.7, "Star Wars", 1977));
        list.add(new Movie(9.9, "Empire Strikes back", 1980));
        list.add(new Movie(3.2, "Return of the jedi", 1983));

        // Sort the items based on the pararmeter mentioned in the compareTo method
        // .Here the sort pareameter is the year of the release.
        Collections.sort(list);

        System.out.println("Movie after sorting :"+"\n");
        for (Movie movie : list) {
            System.out.println(movie.getName() + " " + movie.getRating() + " " + movie.getYear());
        }
    }

}

我有上述 compareTo 的用例。我想了解 compareTo 方法在幕后的作用。当我重写compareTo方法并决定按“年份”排序时;比较是如何发生的?我可以理解为根据比较结果返回1-10。但是下面这行代码是如何进行比较的:

 return this.year - m.year; 

当我说this.year时,代码是否采用第一项,即

8.8, "Force Awakens", 2015

并与列表中的所有元素进行比较,即传递到上面的 compareTo 方法中的 movie 对象的元素?

对象比较是如何发生的?

最佳答案

Here's Collections.sort(..) 方法的文档,内容如下:

Sorts the specified list into ascending order, according to the natural ordering of its elements. All elements in the list must implement the Comparable interface. Furthermore, all elements in the list must be mutually comparable (that is, e1.compareTo(e2) must not throw a ClassCastException for any elements e1 and e2 in the list).

这就是排序的完成方式:

This implementation dumps the specified list into an array, sorts the array, and iterates over the list resetting each element from the corresponding position in the array. This avoids the n2 log(n) performance that would result from attempting to sort a linked list in place.

所以是的,所以你是对的。它从列表中选取每个元素,并使用 compareTo 将其与其他元素进行比较。

关于java - 'compareTo' 比较用例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55179373/

相关文章:

java - JVM 进程 - 打印每个方法参数

java - 如何使用 foreach 迭代 JavaRDD 并使用 spark java 从每一行中查找特定元素

java - Gradle - 将一个项目的类文件包含在另一个项目中

collections - 如何在迭代集合的同时修改集合?

java - 如果 compareTo() 返回 0,为什么暗示对象相等?

java - 如何读取直接触发lambda执行的上传文件?

java - 如何从 wsdl 生成请求和响应类?

Java : How to do aggregation over a list supporting min, 每组中的最大值、平均值、最后一种聚合

java - 比较两个集合用于比较两个文本文件的添加、删除、修改

java - 缓存类似集合的集合