The difference between the new line (char []) and char []. Tostring

The result for the following two code blocks in Java is different. I am trying to understand why.

private String sortChars(String s){
      char[] arr = s.toCharArray(); //creating new char[]
       Arrays.sort(arr); //sorting that array
        return new String(arr);  
    }

This returns a string with sorted characters as expected.

private String sortChars(String s){
      char[] arr = s.toCharArray(); //creating new char[]
       Arrays.sort(arr); //sorting that array
        return arr.toString();
    }

Unfortunately. To blame! Use to compare two lines. The output in the second line looks like many people think - [C @ 2e0ece65

Thank!

+4
source share
1 answer

In Java toString, an array is printed [, then a character representing the type of the array element ( Cin this case), and then the hash code of the identifier. So, in your case, are you sure that it returns the original string, and not something like [C@f4e6d?

, new String(arr). , char[] String. Arrays.toString(arr)

, arr.toString() - [Cf4e6d, , Object.toString

getClass().getName() + '@' + Integer.toHexString(hashCode())

char getName() [C. :

System.out.println(arr.getClass().getName());

Object.hashCode() , , . , "" , .. , . arr.toString() :

String s = "fdsa";
char[] arr = s.toCharArray();
char[] arr2 = s.toCharArray();
System.out.println(arr.toString());
System.out.println(arr2.toString());

:

[C@4b7c8f7f
[C@5eb10190

, String, , . , string1.equals(string2) , ==, == .

+7

Source: https://habr.com/ru/post/1541949/


All Articles