import java.util.Arrays; public class HashTest { private String str; public HashTest(String str) { this.str = str; } @Override public String toString() { return this.str; } public static void main(String args[]) { HashTest h1 = new HashTest("2"); String s1 = new String("1"); Object arr[] = new Object[2]; arr[0] = h1; arr[1] = s1; Arrays.sort(arr); for (Object o : arr) { System.out.print(o + " "); } } } |
1 answer
In Arrays.sort(arr) elements are cast to the Comparable interface for comparison. In order to avoid this error, you need HashSet implement Comparable .
- If
HashTestused inComparable, it will be aClassCastException, since the array is of typeObject, and its contents are not cast one to the other. In this case, it is necessary forArrays.sorttoArrays.sortsecond parameter to theComparatorwith theinstanceOfinside for example. - iksuy 2:51 - Rather, there will be a ClassCastException when the compareTo (String s) of the String is called, since compareTo (String s) compares with a string - Ilya Gribun
- Although yes, you were right - Ilya Gribun
|
Arrays.sort(arr);, sorting needs comparable elements - zRrr