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 + " "); } } } 
  • Each line of code is separated by 4 spaces from the beginning of the line. - post_zeew Nov.
  • 2
    By the way, the line number is written in the stack trace. - post_zeew Nov.
  • one
    in Arrays.sort(arr); , sorting needs comparable elements - zRrr

1 answer 1

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 HashTest used in Comparable , it will be a ClassCastException , since the array is of type Object , and its contents are not cast one to the other. In this case, it is necessary for Arrays.sort to Arrays.sort second parameter to the Comparator with the instanceOf inside 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