Difference between new String(char[]) and char[].t

2019-06-27 17:20发布

The output for 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 one 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();
    }

Sorry. My bad! Using to compare two strings. The output to second string looks like this as suggested by many - [C@2e0ece65

Thanks!

1条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-06-27 17:50

In Java, toString on an array prints [, then a character representing the array element type (C in this case) and then the identity hash code. So in your case, are you sure it is returning the original string and not something like [C@f4e6d?

Either way, you should use new String(arr). This is the shortest, neatest, way of converting a char[] back to a String. You could also use Arrays.toString(arr)

Related trivia

The reason that your arr.toString() method returns something like [Cf4e6d is that Object.toString returns

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

For a char array, getName() returns the string [C. For your program you can see this with the code:

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

The second part of the result, Object.hashCode(), returns a number based on the object's memory address, not the array contents. This is because by default the definition of "equals" for an object is reference equality, i.e. two objects are the same only if they are the same referenced object in memory. You will therefore get different arr.toString() values for two arrays based on the same string:

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

gives:

[C@4b7c8f7f
[C@5eb10190

Note that this is different for the String class where the equality rules are overridden to make it have value equality. However, you should always use string1.equals(string2) to test for string equality, and not == as the == method will still test for memory location.

查看更多
登录 后发表回答