打印 Java 数组的最简单方法是什么?
在 Java 中,数组不会覆盖 toString()
,因此,如果您尝试直接打印数组,则会得到 className
+ '@' + hashCode
,由 Object.toString 定义()
:
int[] intArray = new int[] {1, 2, 3, 4, 5};
System.out.println(intArray); // Prints something like '[I@3343c8b3'
但通常,我们实际上想要更像 [1, 2, 3, 4, 5]
的东西。 最简单的方法是什么? 以下是一些输入和输出示例:
// Array of primitives:
int[] intArray = new int[] {1, 2, 3, 4, 5};
// Output: [1, 2, 3, 4, 5]
// Array of object references:
String[] strArray = new String[] {"John", "Mary", "Bob"};
// Output: [John, Mary, Bob]
In Java, arrays don't override toString()
, so if you try to print one directly, you get the className
+ '@' + the hex of the hashCode
of the array, as defined by Object.toString()
:
int[] intArray = new int[] {1, 2, 3, 4, 5};
System.out.println(intArray); // Prints something like '[I@3343c8b3'
But usually, we'd actually want something more like [1, 2, 3, 4, 5]
. What's the simplest way of doing that? Here are some example inputs and outputs:
// Array of primitives:
int[] intArray = new int[] {1, 2, 3, 4, 5};
// Output: [1, 2, 3, 4, 5]
// Array of object references:
String[] strArray = new String[] {"John", "Mary", "Bob"};
// Output: [John, Mary, Bob]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(30)
从 Java 5 开始,您可以使用
Arrays.toString(arr)
或Arrays.deepToString(arr)
< /a> 用于数组中的数组。 请注意,Object[]
版本对数组中的每个对象调用.toString()
。 输出甚至按照您要求的方式进行装饰。示例:
简单数组:
输出:
<前><代码>[约翰、玛丽、鲍勃]
嵌套数组:
输出:
<前><代码>[[Ljava.lang.String;@106d69c, [Ljava.lang.String;@52e922]
[[约翰、玛丽]、[爱丽丝、鲍勃]]
double
数组:输出:
<前><代码>[7.0、9.0、5.0、1.0、3.0]
int
数组:输出:
<前><代码>[7, 9, 5, 1, 3 ]
Since Java 5 you can use
Arrays.toString(arr)
orArrays.deepToString(arr)
for arrays within arrays. Note that theObject[]
version calls.toString()
on each object in the array. The output is even decorated in the exact way you're asking.Examples:
Simple Array:
Output:
Nested Array:
Output:
double
Array:Output:
int
Array:Output:
始终首先检查标准库。
然后尝试:
或者如果您的数组包含其他数组作为元素:
Always check the standard libraries first.
Then try:
or if your array contains other arrays as elements:
不过,很高兴知道,至于“始终首先检查标准库”,我永远不会偶然发现 Arrays.toString( myarray ) 的技巧
——因为我专注于类型myarray 以了解如何执行此操作。 我不想迭代这个事情:我想要一个简单的调用来使其结果类似于我在 Eclipse 调试器中看到的结果,而 myarray.toString() 只是没有这样做。
This is nice to know, however, as for "always check the standard libraries first" I'd never have stumbled upon the trick of
Arrays.toString( myarray )
--since I was concentrating on the type of myarray to see how to do this. I didn't want to have to iterate through the thing: I wanted an easy call to make it come out similar to what I see in the Eclipse debugger and myarray.toString() just wasn't doing it.
在 JDK1.8 中,您可以使用聚合操作和 lambda 表达式:
In JDK1.8 you can use aggregate operations and a lambda expression:
Arrays.toString
作为直接答案,几个人提供的解决方案,包括@Esko,使用
数组。 toString
和Arrays.deepToString
方法,简直是最好的。Java 8 - Stream.collect(joining())、Stream.forEach
下面我尝试列出一些建议的其他方法,尝试进行一些改进,其中最值得注意的补充是使用
Stream.collect< /code>
运算符,使用
joining
Collector
,模仿String.join
正在执行的操作。Arrays.toString
As a direct answer, the solution provided by several, including @Esko, using the
Arrays.toString
andArrays.deepToString
methods, is simply the best.Java 8 - Stream.collect(joining()), Stream.forEach
Below I try to list some of the other methods suggested, attempting to improve a little, with the most notable addition being the use of the
Stream.collect
operator, using ajoining
Collector
, to mimic what theString.join
is doing.从 Java 8 开始,还可以利用 String 类 打印出数组元素,不带括号,并用选择的分隔符分隔(这是下面所示示例中的空格字符):
输出将为“Hey there amigo!”。
Starting with Java 8, one could also take advantage of the
join()
method provided by the String class to print out array elements, without the brackets, and separated by a delimiter of choice (which is the space character for the example shown below):The output will be "Hey there amigo!".
在 Java 8 之前,
我们可以使用 Arrays.toString(array) 来打印一维数组,使用 Arrays.deepToString(array) 来打印多维数组。
Java 8
现在我们可以选择使用 Stream 和 lambda 来打印数组。
打印一维数组:
输出为:
打印多维数组
以防万一我们想要打印多维数组,我们可以使用 Arrays.deepToString(array) 如下:
现在要观察的一点是方法 Arrays.stream(T[])< /code>,在
int[]
的情况下返回Stream
,然后方法flatMapToInt()
映射每个元素流的内容,其中包含通过将提供的映射函数应用于每个元素而生成的映射流的内容。输出是:
Prior to Java 8
We could have used
Arrays.toString(array)
to print one dimensional array andArrays.deepToString(array)
for multi-dimensional arrays.Java 8
Now we have got the option of
Stream
andlambda
to print the array.Printing One dimensional Array:
The output is:
Printing Multi-dimensional Array
Just in case we want to print multi-dimensional array we can use
Arrays.deepToString(array)
as:Now the point to observe is that the method
Arrays.stream(T[])
, which in case ofint[]
returns usStream<int[]>
and then methodflatMapToInt()
maps each element of stream with the contents of a mapped stream produced by applying the provided mapping function to each element.The output is:
如果您使用的是 Java 1.4,您可以这样做:(
当然,这也适用于 1.5+。)
If you're using Java 1.4, you can instead do:
(This works in 1.5+ too, of course.)
Arrays.deepToString(arr)
仅打印一行。要真正将表格打印为二维表格,我必须这样做:
Arrays.deepToString(arr) 方法似乎应该采用分隔符字符串,但不幸的是它没有。
Arrays.deepToString(arr)
only prints on one line.To actually get a table to print as a two dimensional table, I had to do this:
It seems like the
Arrays.deepToString(arr)
method should take a separator string, but unfortunately it doesn't.在 Java 中打印数组的不同方法:
简单的方法
使用
toString()
打印数组的数组
资源:访问数组
Different Ways to Print Arrays in Java:
Simple Way
Using
toString()
Printing Array of Arrays
Resource: Access An Array
在我看来,使用常规 for 循环是打印数组的最简单方法。
这里有一个基于 intArray 的示例代码,
它提供了您的输出
1, 2, 3, 4, 5
Using regular for loop is the simplest way of printing array in my opinion.
Here you have a sample code based on your intArray
It gives output as yours
1, 2, 3, 4, 5
无论您使用哪个 JDK 版本,它都应该始终有效:
如果
Array
包含对象,它就会有效。 如果Array
包含原始类型,您可以使用包装类而不是将原始类型直接存储为..示例:
将其替换为:
更新:
是的! 值得一提的是,将数组转换为对象数组或使用对象数组的成本很高,并且可能会减慢执行速度。 这是由 java 的本质(称为自动装箱)发生的。
因此仅用于打印目的,不应使用。 我们可以创建一个函数,它接受一个数组作为参数并打印所需的格式:
It should always work whichever JDK version you use:
It will work if the
Array
contains Objects. If theArray
contains primitive types, you can use wrapper classes instead storing the primitive directly as..Example:
Replace it with:
Update :
Yes ! this is to be mention that converting an array to an object array OR to use the Object's array is costly and may slow the execution. it happens by the nature of java called autoboxing.
So only for printing purpose, It should not be used. we can make a function which takes an array as parameter and prints the desired format as
我在 Vanilla #Java 中发现了这篇文章最近。 编写
Arrays.toString(arr);
,然后一直导入java.util.Arrays;
不是很方便。请注意,这无论如何都不是永久修复。 只是一个可以使调试更简单的技巧。
直接打印数组给出内部表示和 hashCode。 现在,所有类都将
Object
作为父类型。 那么,为什么不破解Object.toString()
呢? 如果不进行修改,Object 类如下所示:如果将其更改为:
通过将以下内容添加到命令行,可以简单地将这个修改后的类添加到类路径中:
-Xbootclasspath/p:target/classes.
现在,随着 Java 5 以来
deepToString(..)
的可用性,toString(..)
可以轻松更改为deepToString(..)
code> 添加对包含其他数组的数组的支持。我发现这是一个非常有用的 hack,如果 Java 可以简单地添加这个就太好了。 我了解拥有非常大的数组的潜在问题,因为字符串表示可能会出现问题。 也许会传递诸如 System.out 或 PrintWriter 之类的东西来应对这种情况。
I came across this post in Vanilla #Java recently. It's not very convenient writing
Arrays.toString(arr);
, then importingjava.util.Arrays;
all the time.Please note, this is not a permanent fix by any means. Just a hack that can make debugging simpler.
Printing an array directly gives the internal representation and the hashCode. Now, all classes have
Object
as the parent-type. So, why not hack theObject.toString()
? Without modification, the Object class looks like this:What if this is changed to:
This modded class may simply be added to the class path by adding the following to the command line:
-Xbootclasspath/p:target/classes
.Now, with the availability of
deepToString(..)
since Java 5, thetoString(..)
can easily be changed todeepToString(..)
to add support for arrays that contain other arrays.I found this to be a quite useful hack and it would be great if Java could simply add this. I understand potential issues with having very large arrays since the string representations could be problematic. Maybe pass something like a
System.out
or aPrintWriter
for such eventualities.在java 8中这很容易。 Stream有两个关键字
Arrays.stream(intArray).forEach
方法参考:
::println
如果你想在同一行打印数组中的所有元素,那么只需使用
print
而不是 < code>println 即另一种没有方法引用的方法只需使用:
In java 8 it is easy. there are two keywords
Arrays.stream(intArray).forEach
method reference:
::println
If you want to print all elements in the array in the same line, then just use
print
instead ofprintln
i.e.Another way without method reference just use:
您可以循环遍历数组,在循环时打印出每个项目。 例如:
输出:
You could loop through the array, printing out each item, as you loop. For example:
Output:
在 JAVA 中,无需使用任何循环即可打印数组,这是非常简单的方法。
-> 对于单个或简单数组:
输出:
<前><代码> [1, 2, 3, 4, 5, 6]
-> 所以,这个二维数组不能用Arrays.toString()打印
输出:
<预><代码> [[1, 2, 3, 4, 5, 6, 7], [8, 9, 10, 11, 12, 13, 14]]
It is very simple way to print array without using any loop in JAVA.
-> For, Single or simple array:
The Output :
-> So, this 2D array can't be printed with Arrays.toString()
The Output:
打印数组有以下几种方式
There Are Following way to print Array
如果您的数组是 char[] 类型,还有另一种方法:
打印
There's one additional way if your array is of type char[]:
prints
我尝试过的一个简化的快捷方式是这样的:
它将打印
Noloops required in this method and it is best for Small arrays only
A simplified shortcut I've tried is this:
It will print
No loops required in this approach and it is best for small arrays only
使用 org.apache.commons.lang3.StringUtils.join(*) 方法可以是一个选项
例如:
我使用了以下依赖项
Using org.apache.commons.lang3.StringUtils.join(*) methods can be an option
For example:
I used the following dependency
For-each 循环也可用于打印数组元素:
For-each loop can also be used to print elements of array:
要添加到所有答案中,也可以选择将对象打印为 JSON 字符串。
使用 Jackson:
使用 Gson:
To add to all the answers, printing the object as a JSON string is also an option.
Using Jackson:
Using Gson:
这里是一个可能的打印函数:
例如,如果 main 是这样的,
则输出将为 { [1] [2] [3] [4] }
Here a possible printing function:
For example, if main is like this
the output will be { [1] [2] [3] [4] }
这被标记为打印字节[]的重复项。 注意:对于字节数组,还有其他可能合适的方法。
如果它包含 ISO-8859-1 字符,您可以将其打印为字符串。
或者如果它包含 UTF-8 字符串
或者您想将其打印为十六进制。
或者如果您想将其打印为 base64。
或者如果您想打印有符号字节值的数组
或如果您想打印无符号字节值的数组
This is marked as a duplicate for printing a byte[]. Note: for a byte array there are additional methods which may be appropriate.
You can print it as a String if it contains ISO-8859-1 chars.
or if it contains a UTF-8 string
or if you want print it as hexadecimal.
or if you want print it as base64.
or if you want to print an array of signed byte values
or if you want to print an array of unsigned byte values
如果您运行的是 jdk 8.
输出:
if you are running jdk 8.
output:
如果您使用的是 Java 11
输出:
If you are using Java 11
Output :
在java 8中:
In java 8 :