import java.util.*;
class A implements Comparable<A>
{
int a;
public int compareTo(A other)
{
A a1 = (A) other; //No need of cast
if(this.a == other.a ) return 0;
if(this.a < other.a ) return -1;
return 1;
}
}
class ctest
{
public static void main(String args[])
{
String[] names = {"OOP","BITS","PILANI"};
Arrays.sort(names);
int[] data = { 10,-45,87,0,20,21 };
Arrays.sort(data);
A[] arr = new A[5];
arr[0] = new A();
arr[1] = new A();
arr[2] = new A();
arr[3] = new A();
arr[4] = new A();
Arrays.sort(arr);
}
}
这给出了错误:
Exception in thread "main" java.lang.ClassCastException: A cannot be cast to java.lang.Comparable
at java.util.ComparableTimSort.countRunAndMakeAscending(Unknown Source)
at java.util.ComparableTimSort.sort(Unknown Source)
at java.util.ComparableTimSort.sort(Unknown Source)
at java.util.Arrays.sort(Unknown Source)
答案 0 :(得分:1)
线程“main”中的异常java.lang.ClassCastException:A无法强制转换为java.lang.Comparable
这意味着您运行的A
版本不具备可比性。很可能你有两个版本的A,或者你没有正确构建类。我建议使用IDE来构建类,并进行干净的构建应该解决这个问题。