在Java原始的印刷阵列 [英] Printing array of primitives in Java
问题描述
我有两个数组:
的char [] =字符{'1','2','3'};
INT []数= {1,2,3};
为什么打完电话后 System.out.print(字符)
我收到 123
过了一会 System.out.print(数字)
我有像水木清华 [C @ 9304b1
?
更重要的是,在打印之后 System.out.print(ABC+字符)
我也越来越 ABC [C @ 9304b1
。
我知道 [C @ 9304b1
等于chars.toString()方法,但为什么有时System.out.print只打印它的元素?
的PrintStream
,类型的System.out
,有几个重载的打印
方法,其中一个需要的字符数组(的char []
):
打印字符数组。该
字符根据平台的转换成字节
默认字符编码,并写入这些字节在完全
写(int)方法的方式。
块引用>
块引用>因此,在你的第一个例子中,你得到的
123 打印。然而, 的PrintStream
不具有过载打印
可以接受INT []
作为参数,因此,你最终调用<一个href=\"http://download.oracle.com/javase/6/docs/api/java/io/PrintStream.html#print%28java.lang.Object%29\"相对=nofollow>打印(对象)
,它使用的的的toString
方法对象
,包括它的类型和它的哈希code的。为了打印
INT []
,你可以使用的Arrays.toString()
来代替。I've got two arrays:
char[] chars = { '1', '2', '3' }; int[] numbers = { 1, 2, 3 };
Why after calling
System.out.print(chars)
I'm getting123
while afterSystem.out.print(numbers)
I've got smth like[C@9304b1
?What is more, after printing
System.out.print("abc" + chars)
I'm also gettingabc[C@9304b1
.I know that
[C@9304b1
equals chars.toString() method but why sometimes System.out.print print only its elements?解决方案
PrintStream
, the type ofSystem.out
, has several overloads for thechar[]
):Prints 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.
Thus, in your first example, you get
123
printed. However,PrintStream
doesn't have an overload forint[]
as an argument, thus, you end up invokingprint(Object)
, which will use thetoString
method of anObject
, consisting of its type and its hashcode.In order to print an
int[]
, you can useArrays.toString()
instead.这篇关于在Java原始的印刷阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!