I want to compare a new class called CalendarDate. I made an interface Comparable, and I make the public class CalendarDate implementing Comparable. I also wrote a compareTo(CalendarDate Other) method in the class.
However, when I try Collections.sort(birthday), it says Bound mismatch. (It has details: Bound mismatch: The generic method sort(List) of type Collections is not applicable for the arguments (ArrayList). The inferred type CalendarDate is not a valid substitute for the bounded parameter >)
what is wrong with my code? Thanks.
P.S. There is a RED line under the word sort in CalendarDateTest.java.
Comparable.java
package Chapter10;
public interface Comparable<T> {
public int compareTo(T other);
}
CalendarDate.java
package Chapter10;
public class CalendarDate implements Comparable<CalendarDate> {
private int month;
private int day;
public CalendarDate(int month, int day) {
this.month = month;
this.day = day;
}
public int compareTo(CalendarDate other) {
if (month != other.month) {
return month - other.month;
}
else {
return day - other.day;
}
}
public String toString() {
return month + "/" + day;
}
}
CalendarDateTest.java
package Chapter10;
import java.util.*;
public class CalendarDateTest {
public static void main (String[] args) {
ArrayList<CalendarDate> birthday = new ArrayList<CalendarDate>();
birthday.add(new CalendarDate(1, 23));
birthday.add(new CalendarDate(5, 18));
birthday.add(new CalendarDate(12, 17));
birthday.add(new CalendarDate(2, 29));
birthday.add(new CalendarDate(8, 6));
System.out.println("birthdays = " + birthday);
Collections.sort(birthday);
System.out.println("birthdays = " + birthday);
}
}
The problem is that you have re-defined the Comparable<T>
interface that Java has already defined. As far as Java is concerned, these are two entirely different, unrelated interfaces, despite having the same name. The Collections.sort
method knows about java.lang.Comparable<T>
, but it has no idea about your Chapter10.Comparable<T>
.
Remove Comparable.java file from your project, recompile, and run; this should fix the problem.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments