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);
}
}
This gives the error:
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)
This means the version of
Ayou are running is not Comparable. Most likely you have two versions of A or you didn’t build the class correctly. I suggest using an IDE to build you classes and doing a clean build should fix this.BTW: All your A are the same, so sorting them won’t do anything. You can fix these once you have fixed the build.