Printing array of primitives in Java

戏子无情 提交于 2019-12-31 04:56:23

问题


I've got two arrays:

char[] chars = { '1', '2', '3' };
int[] numbers = { 1, 2, 3 };

Why after calling System.out.print(chars) I'm getting 123 while after System.out.print(numbers) I've got smth like [C@9304b1 ?

What is more, after printing System.out.print("abc" + chars) I'm also getting abc[C@9304b1 .

I know that [C@9304b1 equals chars.toString() method but why sometimes System.out.print print only its elements?


回答1:


PrintStream, the type of System.out, has several overloads for the print method, one of which takes an array of characters (char[]):

public void print(char[] s)

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 for print that can accept an int[] as an argument, thus, you end up invoking print(Object), which will use the toString method of an Object, consisting of its type and its hashcode.

In order to print an int[], you can use Arrays.toString() instead.




回答2:


Because the default toString() just prints out a default "here's what/where this object is", and different types do different things.




回答3:


The reason is that System.out.print can accept a char array and convert it into printable text, thus giving the string "123", but the array of integers does not have an implicit method to display itself as text, so it just displays the address of the array.



来源:https://stackoverflow.com/questions/7918147/printing-array-of-primitives-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!