在Java中打印char和int数组之间的区别 [英] Difference between printing char and int arrays in Java

查看:81
本文介绍了在Java中打印char和int数组之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我运行以下代码时,我得到了数组的地址:

When I run the following code I get the address of the array:

int arr[] = {2,5,3};
System.out.println(arr); // [I@3fe993

但是,当我声明一个字符数组并以相同的方式打印它时,它将为我提供数组的实际内容.为什么?

But when I declare a character array and print it the same way it gives me the actual content of the array. Why?

char ch[] = {'a','b','c'};
System.out.println(ch); // abc

推荐答案

PrintStream(即System.out是)具有专用的方法重载

Class PrintStream (which is what System.out is) has a dedicated method overload println(char[]) which prints the characters of a char array.

它对其他数组没有特殊的重载,因此当您传递int[]时,调用的方法是

It has no special overloads for other arrays, so when you pass an int[] the called method is println(Object). That method converts the passed object to a string by calling its toString() method.

所有数组的toString()方法只是继承的默认方法 Arrays.toString(int[]) 以获得int数组内容的字符串表示形式.

The toString() method for all arrays is simply the default one inherited from class Object, which displays their class name and default hashcode, which is why it's not so informative. You can use Arrays.toString(int[]) to get a string representation of your int array's contents.

P.S.与文档所说的相反,对象的默认哈希码通常不是对象的地址,而是随机生成的数字.

P.S. Contrary to what the doc says, the default hashcode of an object is not typically the object's address, but a randomly generated number.

这篇关于在Java中打印char和int数组之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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