简体   繁体   English

你如何编写一个在java中打印数组中对象的方法?

[英]How do you write a method that prints objects in a array in java?

如何在java中打印数组中的对象?

There are several useful toString() and deepToString() methods in java.util.Arrays class. java.util.Arrays类中有几个有用的toString()deepToString()方法。

String[] strings = { "foo", "bar", "waa" };
System.out.println(Arrays.toString(strings)); // [foo, bar, waa]

An alternative is to just loop over them yourself and print each item separately. 另一种方法是自己循环遍历它们并分别打印每个项目。

Using Apache Commons Lang : 使用Apache Commons Lang

org.apache.commons.lang.StringUtils.join(Arrays.asList(strings), ", ");

Using Spring Core: 使用Spring Core:

org.springframework.util.StringUtils.collectionToDelimitedString(Arrays.asList(strings), ", ");

You can do it using for loop. 你可以使用for循环来做到这一点。

Here's example : 这是一个例子:

  String[] colors = {"red","blue","black","green","yellow"};
  for (String color : colors) {
   System.out.println(color);
  }

Also check : What's the simplest way to print a Java array? 还要检查: 打印Java数组的最简单方法是什么?

As quoted by Esko in above link is best answer: 正如Esko在上面链接引用的链接是最佳答案:

In Java 5 Arrays.toString(arr) or Arrays.deepToString(arr) for arrays within arrays. 在Java 5 Arrays.toString(arr)Arrays.deepToString(arr)中,用于数组中的数组。

Note that Object[] version calls .toString() of each object in array. 请注意,Object []版本调用数组中每个对象的.toString() If my memory serves me correct, the output is even decorated in the exact way you're asking. 如果我的记忆对我有用,那么输出甚至会以您要求的方式进行装饰。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM