我在使用 collections.sort 时遇到问题,因为它没有对任何内容进行排序。我有两个类,其中一个类有一个比较日期的compareTo 方法,另一个类有一个对日期进行排序的Collections.sort 方法。我的代码编译并运行没有错误,但 ArrayList 未排序,有人可以告诉我我做错了什么以及为什么 Collections.sort 不起作用。
这是代码:
public class CalendarDate implements Comparable<CalendarDate>{
private int month;
private int day;
//Constructor
public CalendarDate(int month, int day){
this.month = month;
this.day = day;
}
//CompareTo method
public int CompareTo(CalendarDate other){
if(month != other.month){
return month - other.month;
}
else {
return day - other.day;
}
}
//Getters
public int getMonth(){
return month;
}
public int getDay(){
return day;
}
//toString method
public String toString(){
return month + "/" + day;
}
public int compareTo(CalendarDate other) {
return 0;
}
}
<小时/>
import java.util.*;
public class CalendarDateSort {
public static void main(String[] args){
ArrayList<CalendarDate> list = new ArrayList<CalendarDate>();
list.add(new CalendarDate(1, 11));
list.add(new CalendarDate(5, 15 ));
list.add(new CalendarDate(3, 8));
list.add(new CalendarDate(7, 10));
list.add(new CalendarDate(3, 16));
System.out.println("dates before sorting = " + list);
Collections.sort(list);
System.out.println("dates after sorting = " + list);
}
}
最佳答案
您进行比较的 CompareTo
方法有一个拼写错误,并且名称不同。 Java 标识符区分大小写。实际调用的 compareTo
始终返回 0(表示所有元素都相等)。
public class CalendarDate implements Comparable<CalendarDate>{
// doesn't get called by sort
public int CompareTo(CalendarDate other){
if(month != other.month){
return month - other.month;
}
else {
return day - other.day;
}
}
// gets called by sort
public int compareTo(CalendarDate other) {
return 0;
}
}
使用@Override
注释。如果犯这种错误,将会产生编译错误。
另请参阅Overriding and Hiding Methods .
When overriding a method, you might want to use the @Override annotation that instructs the compiler that you intend to override a method in the superclass. If, for some reason, the compiler detects that the method does not exist in one of the superclasses, then it will generate an error.
关于java - CompareTo 和 collections.sort() 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22339027/