什么是打印Java数组的最简单方法?
在Java中,数组不覆盖 toString()
,因此,如果您尝试直接打印一个,则获得 className
+'@' + href =“ https://en.wikipedia.org/wiki/java_hashcode()” rel =“ noreferrer”> 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]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(30)
在Java中打印数组的不同方法:
简单的方式
使用
toString()
阵列的打印数组
]阵列中的“ java”/“ rel =“ noreferrer”>访问数组
Different Ways to Print Arrays in Java:
Simple Way
Using
toString()
Printing Array of Arrays
Resource: Access An Array
在我看来,使用常规 循环是打印阵列的最简单方法。
在这里,您有一个基于您的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的性质发生的,称为Autoboxing。
因此,仅出于打印目的,不应使用它。我们可以制作一个函数,该函数以参数为参数并将所需格式打印为
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
我遇到了这篇文章, arrays.tostring(arr); ,然后
java.util.arrays;
始终导入。请注意,无论如何,这不是永久解决方案。只是一个可以使调试变得更简单的黑客。
打印数组直接提供内部表示形式和哈希码。现在,所有类都有
对象
作为父型。那么,为什么不黑客入侵object.tostring()
呢?如果没有修改,对象类看起来像这样:如果将其更改为:
可以通过将以下内容添加到命令行中:
-XbootClassPath/p:target/class代码>。
现在,随着
deepToString的可用性(..)
从Java 5开始,toString(..)
可以轻松地更改为deeptostring(..)添加对包含其他数组的数组的支持。
我发现这是一个非常有用的骇客,如果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中很容易。有两个关键字
arrays.stream(intarray).foreach
方法参考:
:: println
如果要在同一行中打印数组中的所有元素,则只需使用
print
而不是<代码> println ie其他方法没有方法参考,请使用:
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中的任何循环的非常简单的方法。
- &gt;因为,单个或简单的数组:
输出:
- &gt;因此,这个2D数组无法用arrays.tostring()
打印
输出:
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
我尝试过的简化快捷方式是:
它将
在这种方法中打印不需要循环,仅适用于小阵列
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-EAPH循环也可用于打印数组的元素:
For-each loop can also be used to print elements of array:
要添加所有答案,将对象打印为JSON字符串也是一个选项。
使用杰克逊:
使用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 :
由于java 5,您可以使用
arrays.tostring(arr)
或arrays.darrays.deeptoptoString(deeptoString(arr)
< /a>对于数组中的数组。请注意,对象[]
版本调用.toString()
在数组中的每个对象上。输出甚至以您要问的确切方式进行装饰。示例:
简单数组:
输出:
嵌套数组:
输出:
double
数组:输出:
int
数组:输出:
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.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。
下面我尝试列出建议的其他一些方法,试图改进一点,最值得注意的是使用
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开始,也可以利用
join()
方法,由 string class 在没有括号的情况下打印出数组元素,而没有括号,并由选择的定界符(这是下面显示的示例的空间字符):输出将是“嘿,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)
as:现在要观察到的要点是方法
arrays.stream.stream(t [])< /code>,如果是
int []
返回我们stream&lt; int []&gt;
,然后方法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.