在Java原始的印刷阵列 [英] Printing array of primitives in Java

查看:128
本文介绍了在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 [] ):


  

公共无效打印(的char [] S)


  
  

    

打印字符数组。该
    字符根据平台的转换成字节
    默认字符编码,并写入这些字节在完全
    写(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 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?

解决方案

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.

这篇关于在Java原始的印刷阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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