Java的:用字符数组调用println给胡言乱语 [英] Java: println with char array gives gibberish

查看:161
本文介绍了Java的:用字符数组调用println给胡言乱语的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面就是问题所在。这code:

Here's the problem. This code:

String a = "0000";
 System.out.println(a);
char[] b = a.toCharArray();
 System.out.println(b);

返回


0000
0000


但是,这code:


But this code:

String a = "0000";
 System.out.println("String a: " + a);
char[] b = a.toCharArray();
 System.out.println("char[] b: " + b);

返回


String a: 0000
char[] b: [C@56e5b723


在世界上发生了什么事?似乎应该有一个简单的解决方案不够,但我似乎无法推测出来。


What in the world is going on? Seems there should be a simple enough solution, but I can't seem to figure it out.

推荐答案

当你说

System.out.println(b);

这导致调用打印(的char [] S)然后的println()

打印(的char [] S)说的JavaDoc:

The JavaDoc for print(char[] s) says:

打印字符数组。字符被转换成字节
  根据平台的默认字符编码,而这些
  字节被写入在写入(int)方法完全相同的方式

Print an array of characters. The characters are converted into bytes according to the platform's default character encoding, and these bytes are written in exactly the manner of the write(int) method.

所以它执行逐字节打印出来。

So it performs a byte-by-byte print out.

当你说

System.out.println("char[] b: " + b);

这导致调用打印(字符串),所以你实际上做的是附加到字符串对象它调用的toString()对象 - 这一点,因为所有的对象默认情况下,并在阵列,打印值参考(内存地址)。

It results in a call to print(String), and so what you're actually doing is appending to a String an Object which invokes toString() on the Object -- this, as with all Object by default, and in the case of an Array, prints the value of the reference (the memory address).

您可以这样做:

System.out.println("char[] b: " + new String(b));

请注意,这是在你不支付任何头脑编码和使用系统默认意义上的错误的。了解编码宜早不宜迟。

Note that this is "wrong" in the sense that you're not paying any mind to encoding and are using the system default. Learn about encoding sooner rather than later.

这篇关于Java的:用字符数组调用println给胡言乱语的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆