package com.example;
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
MyClass[] ms = {
new MyClass("Monin",119),
new MyClass("Annie",120),
new MyClass("David",99)
};
Arrays.sort(ms);
System.out.println(Arrays.toString(ms));
}
}
interface Comparable<T> {
public int compareTo(T o);
}
class MyClass implements Comparable<MyClass> {
private String name;
private int num;
public MyClass(String name, int num) {
this.name = name;
this.num = num;
}
public int compareTo(MyClass m) {
return this.name.compareTo(m.num);
}
public String toString() {
return name + ":" + num;
}
}
报错:
java.lang.ClassCastException: com.example.MyClass 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:1239)
at com.example.Main.main(Main.java:13)
at java.lang.reflect.Method.invoke(Native Method)
at com.duy.android.compiler.java.Java.run(Unknown Source:335)
at com.duy.ide.javaide.run.activities.ExecuteActivity.executeDex(Unknown Source:42)
at com.duy.ide.javaide.run.activities.ExecuteActivity.exec(Unknown Source:19)
at com.duy.ide.javaide.run.activities.ExecuteActivity.access$100(Unknown Source:0)
at com.duy.ide.javaide.run.activities.ExecuteActivity$1.run(Unknown Source:8)
at java.lang.Thread.run(Thread.java:929)
怎么回事?如何改?