简体   繁体   中英

java String.valueOf issue

I wrote this code:

byte[] test = {-51};
byte[] test2 = {-51};
byte[] test3 = {-51};
System.out.println(String.valueOf(test));
System.out.println(String.valueOf(test2));
System.out.println(String.valueOf(test3));

And i've got a different results:

[B@9304b1
[B@190d11
[B@a90653

Why?

The numbers you're seeing are the hash codes of the array objects .

To see the contents of the arrays, use Arrays.toString() :

System.out.println(Arrays.toString(test));
System.out.println(Arrays.toString(test2));
System.out.println(Arrays.toString(test3));

the toString pf any array doesn't use the values in the array to create the string you can use Arrays.toString(test); for that

String.valueOf does not have a byte[] argument, so it will be processed as Object and the toString() method will be called, since arrays doesn't implements this method, Object.toString() will be process in the array and it's result varies from each instance.

If you want to convert byte[] to String use the constructor String(byte[]) or String(byte[] bytes, Charset charset)

byte[] test = {-51};
byte[] test2 = {-51};
byte[] test3 = {-51};
System.out.println(new String(test));
System.out.println(new String(test2));
System.out.println(new String(test3));

Result:

Í
Í
Í

If you want to view the content of the array use the Arrays.toString(byte[])

byte[] test = {-51};
byte[] test2 = {-51};
byte[] test3 = {-51};
System.out.println(Arrays.toString(test));
System.out.println(Arrays.toString(test2));
System.out.println(Arrays.toString(test3));

Result:

[-51]
[-51]
[-51]

ValueOf() just calls toString() of given object. If you want to print the content of array use Arrays.toString() instead.

因为字节数组没有String.valueOf ,所以当给它byte[] ,它使用String.valueOf(Object obj)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM