所以在这个类中我试图创建一个Starship对象数组,然后使用Arrays.sort按长度排序,在前后打印数组。我的Comparable实现似乎是正确的,我提供了compareTo()方法,但是我收到了以下错误,好像我没有提供正确的实现:
Exception in thread "main" java.lang.ClassCastException: Starship cannot be cast to java.lang.Comparable
at java.util.ComparableTimSort.countRunAndMakeAscending(ComparableTimSort.java:320)
at java.util.ComparableTimSort.sort(ComparableTimSort.java:188)
at java.util.Arrays.sort(Arrays.java:1246)
at Starship.main(Starship.java:44)
我到处都搜索过,但没有发现这个问题。很多,非常感谢任何可以帮助我的代码的人!
import java.util.*;
public class Starship implements Comparable<Starship> {
//fields
private String name;
private String captain;
private int length;
//methods
public Starship (String name, String captain, int length){
this.name=name;
this.captain=captain;
this.length=length;
}
public String getName(){
return name;
}
public String getCaptain(){
return captain;
}
public int getLength(){
return length;
}
public String toString(){
return "(ship="+name+", captain="+captain+", length="+length+"m)";
}
@Override
public int compareTo (Starship other){
if (length<other.length) return -1;
else if(length>other.length) return 1;
else return 0;
}
//test
public static void main(String[] args){
Starship[] ships= {
new Starship("Enterprise-D", "Jean-Luc Picard", 643),
new Starship("Serenity", "Malcolm Reynolds", 82),
new Starship("Galactica", "William Adama", 1445),
new Starship("Millennium Falcon", "Hans Solo", 35)
};
System.out.println("The ships:");
for(int i=0; i<4; i++){
System.out.println(ships[i].toString());
}
Arrays.sort(ships);
System.out.println("After sorting:");
for(int i=0; i<4; i++){
System.out.println(ships[i].toString());
}
}
}