Behavior of String.valueOf () with char [] in list <char []>
I worked with char[]
and Collection
with the below code: -
char[] ch = { 'a', 'b', 'c' };
List<char[]> chList = new ArrayList<char[]>();
chList.add(new char[]{'d','e','f'});
chList.add(new char[]{'g','h','i'});
String chSt = String.valueOf(ch);
String chListSt = chList.toString();
System.out.println(chSt); // outputs abc
System.out.println(chListSt); // outputs [[C@8288f50b, [C@b6d2b94b] instead [def, ghi]
Now I have observed above: -
String chSt = String.valueOf(ch);
I know the above code behavior is correct for char[]
in String.valueOf()
, so for the above code abc
. Now consider the next line.
String chListSt = chList.toString();
Also for the above code, I know what toString()
for is List
defined in AbstractList
, and in the code of this override, toString()
I found buffer.append(next);
which calls the method String.valueOf()
to char[]
which matches next
here.
Therefore, it should also print as [def, ghi]
, as in the direct case with char[]
in lineString chSt = (String.valueOf(ch));
Why is this change in behavior present in both cases when the same method String.valueOf()
is called on char[]
?
source to share
You can see the difference in calling different overloads String.valueOf
. Here's a simpler example:
public class Test {
public static void main(String[] args) {
char[] chars = { 'a', 'b', 'c' };
System.out.println(String.valueOf(chars)); // abc
Object object = chars;
System.out.println(String.valueOf(object)); // [C@...
}
}
The call you found in StringBuffer
or StringBuilder
will just call String.valueOf(Object)
-, which then calls toString()
on the array (after checking the reference is not null). Arrays are not overridden toString
in Java, hence the output you get.
source to share
The code is String chListSt = chList.toString();
simply called toString () the List implementation. List the calls to the toString () implementation for the elements.
Your current list has array objects in the list as elements, so you get the view of array.toString () on the console, which outputs the hexadecimal code printed for char [].
Instead of char [], try storing the string in an array. It will have the same performance and the results will be readable.
source to share