为什么Java中的toString方法似乎不是一个阵列工作 [英] Why does the toString method in java not seem to work for an array
问题描述
我要一个字符数组转换为使用Java中的toString()方法的String对象。下面是测试code我用的一个片段:
I want to convert a character array to a string object using the toString() method in java. Here is a snippet of the test code I used:
import java.util.Arrays;
class toString{
public static void main(String[] args){
char[] Array = {'a', 'b', 'c', 'd', 'e', 'f'};
System.out.println(Array.toString());
}
}
在原则上,它应该打印的 ABCDEF ,但它打印的 [C @ 6e1408 或 [C @ e53108 每个程序的执行时间。我并不需要一个替代了这一点,但想知道为什么会这样。
In principle, it should print abcdef, but it is printing random gibberish of the likes of [C@6e1408 or [C@e53108 each time the program executes. I don't need an alternative out of this but want to know why this is happening.
推荐答案
要得到一个可读的的toString()
,则必须使用<一个href=\"http://docs.oracle.com/javase/6/docs/api/java/util/Arrays.html#toString%28double%5B%5D%29\"><$c$c>Arrays.toString()$c$c>,像这样的:
To get a human-readable toString()
, you must use Arrays.toString()
, like this:
System.out.println(Arrays.toString(Array));
Java的的toString()
一个数组是打印 [
,后跟一个字符重新presenting数组元素的类型(在你的情况 C
为字符
),其次是 @
则数组的标识哈希code(认为它像你将一个内存地址)。
Java's toString()
for an array is to print [
, followed by a character representing the type of the array's elements (in your case C
for char
), followed by @
then the "identity hash code" of the array (think of it like you would a "memory address").
事务的这种悲惨状况通常被认为是一个错误与Java。
This sad state of affairs is generally considered as a "mistake" with java.
请参阅这个答案对其他失误的列表。
See this answer for a list of other "mistakes".
这篇关于为什么Java中的toString方法似乎不是一个阵列工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!