gpt4 book ai didi

java - 'compareTo' 比较用例

转载 作者:行者123 更新时间:2023-12-02 01:36:31 31 4
gpt4 key购买 nike

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/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com