Search code examples
java

Arrays sort misbehavior for Character array


String s5 = "peek";
int i[] = {12, 25, 7, 3, 45};
Arrays.sort(i);

for(int x : i) {
  System.out.print(x + ",");
}

Arrays.sort(s5.toCharArray());

System.out.println(s5); // expected here eekp, but showing peek

for(char c : s5.toCharArray()) {
  System.out.print(c + ",");  //expected here e,e,k,p , but showing p,e,e,k
}

Output:

3,7,12,25,45,peek
p,e,e,k,

for the line System.out.println(s5) I expected "eekp" but it's showing "peek".

for the line System.out.print(c + ",") I expected "e,e,k,p" but it's showing "p,e,e,k"

Arrays sort seems to work well for integers but not for character array, seems like am doing something wrong. could you please tell me?


Solution

  • Strings are immutable (mostly)

    Arrays.sort(s5.toCharArray());

    The above sorts a copy of the character array and does not modify the actual string value array.

    The internal code of toCharArray in JDK 1.8

      char result[] = new char[value.length];
      System.arraycopy(value, 0, result, 0, value.length);
    
    

    Store and sort the copy(new object in a reference)

    char[] copy = s5.toCharArray();
    Arrays.sort(copy);
    

    Do not try unless for fun

      Field field = String.class.getDeclaredField("value");
      field.setAccessible(true);
      String s5 = "peek";
      Arrays.sort((char[]) field.get(s5));
      System.out.println(s5);