我從我的教科書中複製了一個例子,但它拒絕編譯。我在某處做了一個錯字嗎?出於某種原因,在客戶端代碼上,Collections.sort(單詞)不允許程序編譯。任何幫助表示讚賞。代碼從Stuart Reges和Marty Stepp的「Building Java Programs」第2版複製而來。我試圖通過複製來理解它。爲什麼我不能排序這個ArrayList?
該程序應該創造一個CalendarDate對象放入一個ArrayList。通過實現CalendarDate的Comparable接口,我可以使用Collections.sort在ArrayList中排序生日。但是,這不起作用b/c Collections.sort(日期)將不會運行。
客戶端代碼(包含發行):
import java.util.*;
// Short program that creates a list of birthdays of the
// first 5 U.S. Presidents and that puts them into sorted order.
// We can now use Collections.sort for ArrayList<CalendarDate> b/c CalendarDate implements the Comparable interface.
public class CalendarDateTest {
public static void main(String[] args) {
ArrayList<CalendarDate> dates = new ArrayList<CalendarDate>(); // Creates a new ArrayList of 'CalendarDate' object type.
// adds a new CalendarDate object with month = 2 and day = 22 into an element of ArrayList dates, and etc.
dates.add(new CalendarDate(2, 22)); // Washington
dates.add(new CalendarDate(10, 30)); //Adams
dates.add(new CalendarDate(4, 13)); // Jefferson
dates.add(new CalendarDate(3, 16)); // Madison
dates.add(new CalendarDate(4, 28)); // Monroe
System.out.println("birthdays = " + dates); // Before sorting
Collections.sort(dates); // WHY WON'T THIS WORK?
System.out.println("birthdays = " + dates); // After Sorting
}
}
的CalendarDate對象類:
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;
}
// Compares this calendar date to another date
// Dates are compared by month and then by day
public int compareTo(CalendarDate other) {
if (month != other.month) { // If different months
return month - other.month; //negative, positive, or zero
} else { // If same months; compare days instead
return day - other.day; // negative, positive, or zero
}
}
// Accessor for month (b/c month is private)
public int getMonth() {
return this.month;
}
// Accessor for day (b/c day is private)
public int getDay() {
return this.day;
}
// A toString method
public String toString() {
return month + "/" + day;
}
}
可比接口:
public interface Comparable<T> { // T is the generic type (a placeholder for when other classes implement this)
public int compareTo(T other); // placeholder to be implemented; need more specific version into class implementing this.
}
編譯器錯誤:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Bound mismatch: The generic method sort(List<T>) of type Collections is not applicable for the arguments (ArrayList<CalendarDate>). The inferred type CalendarDate is not a valid substitute for the bounded parameter <T extends Comparable<? super T>>
at CalendarDateExample.CalendarDateTest.main(CalendarDateTest.java:21)
提供* exact *編譯器錯誤將是一個好的開始。 – awksp
humm,就我所知,在比較中返回任何正整數或負整數是不正確的..它應該是-1,0或1. –
@ EdwardM.B。 [都能跟得上](http://docs.oracle.com/javase/8/docs/api/java/lang/Comparable.html)。這只是符號/結果是否爲零。 – awksp