如何使用 Java 中的 toString 方法将 int 数组转换为 String [英] How to convert an int array to String with toString method in Java
问题描述
我正在尝试使用 toString(int[])
方法,但我认为我做错了:
http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Arrays.html#toString(int[])
我的代码:
int[] array = new int[lnr.getLineNumber() + 1];int i = 0;System.out.println(array.toString());
输出为:
[I@23fc4bec
我也尝试过这样打印,但是:
System.out.println(new String().toString(array));//**下一行出错**String 类型中的 toString() 方法不适用于参数 (int[])
我从更大更复杂的代码中删除了这段代码,但如果需要,我可以添加它.但这应该提供一般信息.
我正在寻找输出,就像在 Oracle 的文档中一样:
<块引用>字符串表示由数组元素的列表组成,用方括号([]")括起来.相邻元素由字符,"(逗号后跟空格)分隔.
你想要的是 Arrays.toString(int[])
方法:
import java.util.Arrays;int[] array = new int[lnr.getLineNumber() + 1];int i = 0;..System.out.println(Arrays.toString(array));
对于每种不同的原始 Java 类型,都有一个静态的 Arrays.toString
辅助方法;int[]
是这样说的:
public static String toString(int[] a)
返回指定数组内容的字符串表示形式.字符串表示由数组元素的列表组成,用方括号括起来([]"
).相邻元素由字符 ", "
(逗号后跟空格)分隔.元素通过 String.valueOf(int)
转换为字符串.如果 a
为空,则返回 null"
.
I am using trying to use the toString(int[])
method, but I think I am doing it wrong:
http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Arrays.html#toString(int[])
My code:
int[] array = new int[lnr.getLineNumber() + 1];
int i = 0;
System.out.println(array.toString());
The output is:
[I@23fc4bec
Also I tried printing like this, but:
System.out.println(new String().toString(array)); // **error on next line**
The method toString() in the type String is not applicable for the arguments (int[])
I took this code out of bigger and more complex code, but I can add it if needed. But this should give general information.
I am looking for output, like in Oracle's documentation:
The string representation consists of a list of the array's elements, enclosed in square brackets ("[]"). Adjacent elements are separated by the characters ", " (a comma followed by a space).
What you want is the Arrays.toString(int[])
method:
import java.util.Arrays;
int[] array = new int[lnr.getLineNumber() + 1];
int i = 0;
..
System.out.println(Arrays.toString(array));
There is a static Arrays.toString
helper method for every different primitive java type; the one for int[]
says this:
public static String toString(int[] a)
Returns a string representation of the contents of the specified array. The string representation consists of a list of the array's elements, enclosed in square brackets (
"[]"
). Adjacent elements are separated by the characters", "
(a comma followed by a space). Elements are converted to strings as byString.valueOf(int)
. Returns"null"
ifa
is null.
这篇关于如何使用 Java 中的 toString 方法将 int 数组转换为 String的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!