什么是打印Java数组的最简单方法?

发布于 2025-02-09 08:38:49 字数 763 浏览 2 评论 0 原文

在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]

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(30

゛时过境迁 2025-02-16 08:38:50
for(int n: someArray) {
    System.out.println(n+" ");
}
for(int n: someArray) {
    System.out.println(n+" ");
}
暮色兮凉城 2025-02-16 08:38:50

在Java中打印数组的不同方法:

  1. 简单的方式

      list< string> list = new ArrayList< string>();
    list.add(“一个”);
    list.add(“两个”);
    list.add(“三”);
    list.add(“四”);
    //在控制台中打印列表
    system.out.println(list);
     

输出:
[一,二,三,四]

  1. 使用 toString()

     字符串[] array = new String [] {“一个”,“两个”,“三”,“四”};
    system.out.println(arrays.toString(array));
     

输出:[一,两个,三,四个]

  1. 阵列的打印数组

      string [] arr1 = new String [] {“第五”,“第六”};
    字符串[] arr2 = new String [] {“ seventh”,“八”};
    string [] [] arrayofArray = new String [] [] {arr1,arr2};
    system.out.println(arrayofArray);
    system.out.println(arrays.toString(arrayofArray));
    system.out.println(arrays.deeptoString(arrayofArray));
     

输出:[[[ljava.lang.string;@1ad086a [[ljava.lang.string;@10385c1,
[ljava.lang.string;@42719c] [[第五,第六],[第七,第八]]

]阵列中的“ java”/“ rel =“ noreferrer”>访问数组

Different Ways to Print Arrays in Java:

  1. Simple Way

    List<String> list = new ArrayList<String>();
    list.add("One");
    list.add("Two");
    list.add("Three");
    list.add("Four");
    // Print the list in console
    System.out.println(list);
    

Output:
[One, Two, Three, Four]

  1. Using toString()

    String[] array = new String[] { "One", "Two", "Three", "Four" };
    System.out.println(Arrays.toString(array));
    

Output: [One, Two, Three, Four]

  1. Printing Array of Arrays

    String[] arr1 = new String[] { "Fifth", "Sixth" };
    String[] arr2 = new String[] { "Seventh", "Eight" };
    String[][] arrayOfArray = new String[][] { arr1, arr2 };
    System.out.println(arrayOfArray);
    System.out.println(Arrays.toString(arrayOfArray));
    System.out.println(Arrays.deepToString(arrayOfArray));
    

Output: [[Ljava.lang.String;@1ad086a [[Ljava.lang.String;@10385c1,
[Ljava.lang.String;@42719c] [[Fifth, Sixth], [Seventh, Eighth]]

Resource: Access An Array

忘东忘西忘不掉你 2025-02-16 08:38:50

在我看来,使用常规 循环是打印阵列的最简单方法。
在这里,您有一个基于您的intarray的示例代码,

for (int i = 0; i < intArray.length; i++) {
   System.out.print(intArray[i] + ", ");
}

它给出了输出
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

for (int i = 0; i < intArray.length; i++) {
   System.out.print(intArray[i] + ", ");
}

It gives output as yours
1, 2, 3, 4, 5

长梦不多时 2025-02-16 08:38:50

它应该始终使用您使用的JDK版本的哪个:

System.out.println(Arrays.asList(array));

如果 array 包含对象,它将起作用。如果 array 包含原始类型,则可以使用包装类类,而是将原始词直接存储为..

示例:

int[] a = new int[]{1,2,3,4,5};

替换为:

Integer[] a = new Integer[]{1,2,3,4,5};

更新:

是!可以提及的是,将数组转换为对象数组或使用对象的数组是昂贵的,并且可能会减慢执行速度。它是由Java的性质发生的,称为Autoboxing。

因此,仅出于打印目的,不应使用它。我们可以制作一个函数,该函数以参数为参数并将所需格式打印为

public void printArray(int [] a){
        //write printing code
} 

It should always work whichever JDK version you use:

System.out.println(Arrays.asList(array));

It will work if the Array contains Objects. If the Array contains primitive types, you can use wrapper classes instead storing the primitive directly as..

Example:

int[] a = new int[]{1,2,3,4,5};

Replace it with:

Integer[] a = new Integer[]{1,2,3,4,5};

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

public void printArray(int [] a){
        //write printing code
} 
月下客 2025-02-16 08:38:50

我遇到了这篇文章, arrays.tostring(arr); ,然后 java.util.arrays; 始终导入。

请注意,无论如何,这不是永久解决方案。只是一个可以使调试变得更简单的黑客。

打印数组直接提供内部表示形式和哈希码。现在,所有类都有对象作为父型。那么,为什么不黑客入侵 object.tostring()呢?如果没有修改,对象类看起来像这样:

public String toString() {
    return getClass().getName() + "@" + Integer.toHexString(hashCode());
}

如果将其更改为:

public String toString() {
    if (this instanceof boolean[])
        return Arrays.toString((boolean[]) this);
    if (this instanceof byte[])
        return Arrays.toString((byte[]) this);
    if (this instanceof short[])
        return Arrays.toString((short[]) this);
    if (this instanceof char[])
        return Arrays.toString((char[]) this);
    if (this instanceof int[])
        return Arrays.toString((int[]) this);
    if (this instanceof long[])
        return Arrays.toString((long[]) this);
    if (this instanceof float[])
        return Arrays.toString((float[]) this);
    if (this instanceof double[])
        return Arrays.toString((double[]) this);
    if (this instanceof Object[])
        return Arrays.deepToString((Object[]) this);
    return getClass().getName() + "@" + Integer.toHexString(hashCode());
}

可以通过将以下内容添加到命令行中: -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 importing java.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 the Object.toString()? Without modification, the Object class looks like this:

public String toString() {
    return getClass().getName() + "@" + Integer.toHexString(hashCode());
}

What if this is changed to:

public String toString() {
    if (this instanceof boolean[])
        return Arrays.toString((boolean[]) this);
    if (this instanceof byte[])
        return Arrays.toString((byte[]) this);
    if (this instanceof short[])
        return Arrays.toString((short[]) this);
    if (this instanceof char[])
        return Arrays.toString((char[]) this);
    if (this instanceof int[])
        return Arrays.toString((int[]) this);
    if (this instanceof long[])
        return Arrays.toString((long[]) this);
    if (this instanceof float[])
        return Arrays.toString((float[]) this);
    if (this instanceof double[])
        return Arrays.toString((double[]) this);
    if (this instanceof Object[])
        return Arrays.deepToString((Object[]) this);
    return getClass().getName() + "@" + Integer.toHexString(hashCode());
}

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, the toString(..) can easily be changed to deepToString(..) 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.outor a PrintWriter for such eventualities.

雪落纷纷 2025-02-16 08:38:50

在Java 8中很容易。有两个关键字

  1. 流: arrays.stream(intarray).foreach
  2. 方法参考: :: println

      int [] intarray = new int [] {1,2,3,4,5};
    arrays.stream(intarray).foreach(system.out :: println);
     

如果要在同一行中打印数组中的所有元素,则只需使用 print 而不是<代码> println ie

int[] intArray = new int[] {1, 2, 3, 4, 5};
Arrays.stream(intArray).forEach(System.out::print);

其他方法没有方法参考,请使用:

int[] intArray = new int[] {1, 2, 3, 4, 5};
System.out.println(Arrays.toString(intArray));

In java 8 it is easy. there are two keywords

  1. stream: Arrays.stream(intArray).forEach
  2. method reference: ::println

    int[] intArray = new int[] {1, 2, 3, 4, 5};
    Arrays.stream(intArray).forEach(System.out::println);
    

If you want to print all elements in the array in the same line, then just use print instead of println i.e.

int[] intArray = new int[] {1, 2, 3, 4, 5};
Arrays.stream(intArray).forEach(System.out::print);

Another way without method reference just use:

int[] intArray = new int[] {1, 2, 3, 4, 5};
System.out.println(Arrays.toString(intArray));
淡紫姑娘! 2025-02-16 08:38:50

您可以循环循环,在循环时打印出每个项目。例如:

String[] items = {"item 1", "item 2", "item 3"};

for(int i = 0; i < items.length; i++) {

    System.out.println(items[i]);

}

输出:

item 1
item 2
item 3

You could loop through the array, printing out each item, as you loop. For example:

String[] items = {"item 1", "item 2", "item 3"};

for(int i = 0; i < items.length; i++) {

    System.out.println(items[i]);

}

Output:

item 1
item 2
item 3
三五鸿雁 2025-02-16 08:38:50
  • 这是打印数组而无需使用Java中的任何循环的非常简单的方法。

    - &gt;因为,单个或简单的数组:

      int [] array = new int [] {1,2,3,4,5,6};
     system.out.println(arrays.toString(array));
     

    输出:

      [1,2,2,3,4,5,6]
     

    - &gt;因此,这个2D数组无法用arrays.tostring()

    打印

      int [] [] array = new int [] [] {{1,2,2,3,4,5,6,7},{8,9,9,10,11,11,12,13,14 }};
     system.out.println(arrays.deeptoString(array));
     

    输出:

      [[[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:

     int[] array = new int[]{1, 2, 3, 4, 5, 6};
     System.out.println(Arrays.toString(array));
    

    The Output :

          [1, 2, 3, 4, 5, 6]
    

    -> So, this 2D array can't be printed with Arrays.toString()

     int[][] array = new int[][]{{1, 2, 3, 4, 5, 6, 7}, {8, 9, 10, 11, 12,13,14}};
     System.out.println(Arrays.deepToString(array));
    

    The Output:

       [[1, 2, 3, 4, 5, 6, 7], [8, 9, 10, 11, 12, 13, 14]]
    
夏天碎花小短裙 2025-02-16 08:38:50

有以下方式打印数组

 // 1) toString()  
    int[] arrayInt = new int[] {10, 20, 30, 40, 50};  
    System.out.println(Arrays.toString(arrayInt));

// 2 for loop()
    for (int number : arrayInt) {
        System.out.println(number);
    }

// 3 for each()
    for(int x: arrayInt){
         System.out.println(x);
     }

There Are Following way to print Array

 // 1) toString()  
    int[] arrayInt = new int[] {10, 20, 30, 40, 50};  
    System.out.println(Arrays.toString(arrayInt));

// 2 for loop()
    for (int number : arrayInt) {
        System.out.println(number);
    }

// 3 for each()
    for(int x: arrayInt){
         System.out.println(x);
     }
我一向站在原地 2025-02-16 08:38:50

如果您的数组是类型char []:

char A[] = {'a', 'b', 'c'}; 

System.out.println(A); // no other arguments

打印,还有另一种方法

abc

There's one additional way if your array is of type char[]:

char A[] = {'a', 'b', 'c'}; 

System.out.println(A); // no other arguments

prints

abc
貪欢 2025-02-16 08:38:50

我尝试过的简化快捷方式是:

    int x[] = {1,2,3};
    String printableText = Arrays.toString(x).replaceAll("[\\[\\]]", "").replaceAll(", ", "\n");
    System.out.println(printableText);

它将

1
2
3

在这种方法中打印不需要循环,仅适用于小阵列

A simplified shortcut I've tried is this:

    int x[] = {1,2,3};
    String printableText = Arrays.toString(x).replaceAll("[\\[\\]]", "").replaceAll(", ", "\n");
    System.out.println(printableText);

It will print

1
2
3

No loops required in this approach and it is best for small arrays only

轮廓§ 2025-02-16 08:38:50

使用org.apache.commons.lang3.stringutils.join(*)方法可以是一种选项
例如:

String[] strArray = new String[] { "John", "Mary", "Bob" };
String arrayAsCSV = StringUtils.join(strArray, " , ");
System.out.printf("[%s]", arrayAsCSV);
//output: [John , Mary , Bob]

我使用以下依赖性

<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.3.2</version>

Using org.apache.commons.lang3.StringUtils.join(*) methods can be an option
For example:

String[] strArray = new String[] { "John", "Mary", "Bob" };
String arrayAsCSV = StringUtils.join(strArray, " , ");
System.out.printf("[%s]", arrayAsCSV);
//output: [John , Mary , Bob]

I used the following dependency

<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.3.2</version>
柠栀 2025-02-16 08:38:50

for-EAPH循环也可用于打印数组的元素:

int array[] = {1, 2, 3, 4, 5};
for (int i:array)
    System.out.println(i);

For-each loop can also be used to print elements of array:

int array[] = {1, 2, 3, 4, 5};
for (int i:array)
    System.out.println(i);
如梦亦如幻 2025-02-16 08:38:50

要添加所有答案,将对象打印为JSON字符串也是一个选项。

使用杰克逊:

ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
System.out.println(ow.writeValueAsString(anyArray));

使用GSON:

Gson gson = new Gson();
System.out.println(gson.toJson(anyArray));

To add to all the answers, printing the object as a JSON string is also an option.

Using Jackson:

ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
System.out.println(ow.writeValueAsString(anyArray));

Using Gson:

Gson gson = new Gson();
System.out.println(gson.toJson(anyArray));
胡渣熟男 2025-02-16 08:38:50
// array of primitives:
int[] intArray = new int[] {1, 2, 3, 4, 5};

System.out.println(Arrays.toString(intArray));

output: [1, 2, 3, 4, 5]

// array of object references:
String[] strArray = new String[] {"John", "Mary", "Bob"};

System.out.println(Arrays.toString(strArray));

output: [John, Mary, Bob]
// array of primitives:
int[] intArray = new int[] {1, 2, 3, 4, 5};

System.out.println(Arrays.toString(intArray));

output: [1, 2, 3, 4, 5]

// array of object references:
String[] strArray = new String[] {"John", "Mary", "Bob"};

System.out.println(Arrays.toString(strArray));

output: [John, Mary, Bob]
故事还在继续 2025-02-16 08:38:50

这里可能的打印功能:

  public static void printArray (int [] array){
        System.out.print("{ ");
        for (int i = 0; i < array.length; i++){
            System.out.print("[" + array[i] + "] ");
        }
        System.out.print("}");
    }

例如,如果Main是这样,则

public static void main (String [] args){
    int [] array = {1, 2, 3, 4};
    printArray(array);
}

输出将为{[1] [2] [3] [4]}

Here a possible printing function:

  public static void printArray (int [] array){
        System.out.print("{ ");
        for (int i = 0; i < array.length; i++){
            System.out.print("[" + array[i] + "] ");
        }
        System.out.print("}");
    }

For example, if main is like this

public static void main (String [] args){
    int [] array = {1, 2, 3, 4};
    printArray(array);
}

the output will be { [1] [2] [3] [4] }

深居我梦 2025-02-16 08:38:50
public class printer {

    public static void main(String[] args) {
        String a[] = new String[4];
        Scanner sc = new Scanner(System.in);
        System.out.println("enter the data");
        for (int i = 0; i < 4; i++) {
            a[i] = sc.nextLine();
        }
        System.out.println("the entered data is");
        for (String i : a) {
            System.out.println(i);
        }
      }
    }
public class printer {

    public static void main(String[] args) {
        String a[] = new String[4];
        Scanner sc = new Scanner(System.in);
        System.out.println("enter the data");
        for (int i = 0; i < 4; i++) {
            a[i] = sc.nextLine();
        }
        System.out.println("the entered data is");
        for (String i : a) {
            System.out.println(i);
        }
      }
    }
暗藏城府 2025-02-16 08:38:50

这被标记为打印字节[] 。注意:对于字节阵列,还有其他方法可能是合适的。

如果它包含ISO-8859-1字符,则可以将其打印为字符串。

String s = new String(bytes, StandardChars.ISO_8559);
System.out.println(s);
// to reverse
byte[] bytes2 = s.getBytes(StandardChars.ISO_8559);

或者,如果它包含一个UTF-8字符串

String s = new String(bytes, StandardChars.UTF_8);
System.out.println(s);
// to reverse
byte[] bytes2 = s.getBytes(StandardChars.UTF_8);

,或者要将其打印为十六进制。

String s = DatatypeConverter.printHexBinary(bytes);
System.out.println(s);
// to reverse
byte[] bytes2 = DatatypeConverter.parseHexBinary(s);

或者如果您想将其打印为base64。

String s = DatatypeConverter.printBase64Binary(bytes);
System.out.println(s);
// to reverse
byte[] bytes2 = DatatypeConverter.parseBase64Binary(s);

或者如果要打印签名字节值的数组

String s = Arrays.toString(bytes);
System.out.println(s);
// to reverse
String[] split = s.substring(1, s.length() - 1).split(", ");
byte[] bytes2 = new byte[split.length];
for (int i = 0; i < bytes2.length; i++)
    bytes2[i] = Byte.parseByte(split[i]);

,或者要打印一个无符号字节值的数组

String s = Arrays.toString(
               IntStream.range(0, bytes.length).map(i -> bytes[i] & 0xFF).toArray());
System.out.println(s);
// to reverse
String[] split = s.substring(1, s.length() - 1).split(", ");
byte[] bytes2 = new byte[split.length];
for (int i = 0; i < bytes2.length; i++)
    bytes2[i] = (byte) Integer.parseInt(split[i]); // might need a range check.

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.

String s = new String(bytes, StandardChars.ISO_8559);
System.out.println(s);
// to reverse
byte[] bytes2 = s.getBytes(StandardChars.ISO_8559);

or if it contains a UTF-8 string

String s = new String(bytes, StandardChars.UTF_8);
System.out.println(s);
// to reverse
byte[] bytes2 = s.getBytes(StandardChars.UTF_8);

or if you want print it as hexadecimal.

String s = DatatypeConverter.printHexBinary(bytes);
System.out.println(s);
// to reverse
byte[] bytes2 = DatatypeConverter.parseHexBinary(s);

or if you want print it as base64.

String s = DatatypeConverter.printBase64Binary(bytes);
System.out.println(s);
// to reverse
byte[] bytes2 = DatatypeConverter.parseBase64Binary(s);

or if you want to print an array of signed byte values

String s = Arrays.toString(bytes);
System.out.println(s);
// to reverse
String[] split = s.substring(1, s.length() - 1).split(", ");
byte[] bytes2 = new byte[split.length];
for (int i = 0; i < bytes2.length; i++)
    bytes2[i] = Byte.parseByte(split[i]);

or if you want to print an array of unsigned byte values

String s = Arrays.toString(
               IntStream.range(0, bytes.length).map(i -> bytes[i] & 0xFF).toArray());
System.out.println(s);
// to reverse
String[] split = s.substring(1, s.length() - 1).split(", ");
byte[] bytes2 = new byte[split.length];
for (int i = 0; i < bytes2.length; i++)
    bytes2[i] = (byte) Integer.parseInt(split[i]); // might need a range check.
内心荒芜 2025-02-16 08:38:50

如果您正在运行JDK 8。

public static void print(int[] array) {
    StringJoiner joiner = new StringJoiner(",", "[", "]");
    Arrays.stream(array).forEach(element -> joiner.add(element + ""));
    System.out.println(joiner.toString());
}


int[] array = new int[]{7, 3, 5, 1, 3};
print(array);

输出:

[7,3,5,1,3]

if you are running jdk 8.

public static void print(int[] array) {
    StringJoiner joiner = new StringJoiner(",", "[", "]");
    Arrays.stream(array).forEach(element -> joiner.add(element + ""));
    System.out.println(joiner.toString());
}


int[] array = new int[]{7, 3, 5, 1, 3};
print(array);

output:

[7,3,5,1,3]
木槿暧夏七纪年 2025-02-16 08:38:50

如果您使用的是Java 11

import java.util.Arrays;
public class HelloWorld{

     public static void main(String []args){
        String[] array = { "John", "Mahta", "Sara" };
       System.out.println(Arrays.toString(array).replace(",", "").replace("[", "").replace("]", ""));
     }
}

输出:

John Mahta Sara

If you are using Java 11

import java.util.Arrays;
public class HelloWorld{

     public static void main(String []args){
        String[] array = { "John", "Mahta", "Sara" };
       System.out.println(Arrays.toString(array).replace(",", "").replace("[", "").replace("]", ""));
     }
}

Output :

John Mahta Sara
那一片橙海, 2025-02-16 08:38:50

在Java 8中:

Arrays.stream(myArray).forEach(System.out::println);

In java 8 :

Arrays.stream(myArray).forEach(System.out::println);
往日 2025-02-16 08:38:49

由于java 5,您可以使用 arrays.tostring(arr) arrays.darrays.deeptoptoString(deeptoString(arr) < /a>对于数组中的数组。请注意,对象[] 版本调用 .toString()在数组中的每个对象上。输出甚至以您要问的确切方式进行装饰。

示例:

  • 简单数组:

     字符串[] array = new String [] {“ John”,“ Mary”,“ Bob”};
    system.out.println(arrays.toString(array));
     

    输出:

      [约翰,玛丽,鲍勃]
     
  • 嵌套数组:

      string [] [] [] deeparray = new String [] [] {{“ John”,“ Mary”},{“ Alice”,“ Bob”}}};
    //给出不希望的输出:
    system.out.println(arrays.tostring(deeparray));
    //给出所需的输出:
    system.out.println(arrays.deeptoString(deeparray));
     

    输出:

      [[ljava.lang.string;@106d69c,[ljava.lang.string;@52E922]
    [[约翰,玛丽],[爱丽丝,鲍勃]]
     
  • double 数组:

      double [] DoubleArray = {7.0、9.0、5.0、1.0、3.0};
    system.out.println(arrays.toString(doublearray));
     

    输出:

      [7.0,9.0,5.0,1.0,3.0]
     
  • int 数组:

      int [] intarray = {7,9,5,1,3};
    system.out.println(arrays.toString(intarray));
     

    输出:

      [7,9,5,1,3]
     

Since Java 5 you can use Arrays.toString(arr) or Arrays.deepToString(arr) for arrays within arrays. Note that the Object[] version calls .toString() on each object in the array. The output is even decorated in the exact way you're asking.

Examples:

  • Simple Array:

    String[] array = new String[] {"John", "Mary", "Bob"};
    System.out.println(Arrays.toString(array));
    

    Output:

    [John, Mary, Bob]
    
  • Nested Array:

    String[][] deepArray = new String[][] {{"John", "Mary"}, {"Alice", "Bob"}};
    // Gives undesired output:
    System.out.println(Arrays.toString(deepArray));
    // Gives the desired output:
    System.out.println(Arrays.deepToString(deepArray));
    

    Output:

    [[Ljava.lang.String;@106d69c, [Ljava.lang.String;@52e922]
    [[John, Mary], [Alice, Bob]]
    
  • double Array:

    double[] doubleArray = { 7.0, 9.0, 5.0, 1.0, 3.0 };
    System.out.println(Arrays.toString(doubleArray));
    

    Output:

    [7.0, 9.0, 5.0, 1.0, 3.0 ]
    
  • int Array:

    int[] intArray = { 7, 9, 5, 1, 3 };
    System.out.println(Arrays.toString(intArray));
    

    Output:

    [7, 9, 5, 1, 3 ]
    
明月夜 2025-02-16 08:38:49

始终首先检查标准库。

import java.util.Arrays;

然后尝试:

System.out.println(Arrays.toString(array));

或者您的数组包含其他数组作为元素:

System.out.println(Arrays.deepToString(array));

Always check the standard libraries first.

import java.util.Arrays;

Then try:

System.out.println(Arrays.toString(array));

or if your array contains other arrays as elements:

System.out.println(Arrays.deepToString(array));
最冷一天 2025-02-16 08:38:49

但是,很高兴知道,对于“始终首先检查标准库”,我从来没有偶然发现 arrays.tostring.tostring(myarray)

- 我是我专注于类型 的技巧MyArray看看如何做到这一点。我不想迭代事物:我想要一个简单的电话,以使其与我在Eclipse调试器和MyArray.tostring()()()中所看到的类似。

import java.util.Arrays;
.
.
.
System.out.println( Arrays.toString( myarray ) );

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.

import java.util.Arrays;
.
.
.
System.out.println( Arrays.toString( myarray ) );
节枝 2025-02-16 08:38:49

在JDK1.8中,您可以使用聚合操作和lambda表达式:

String[] strArray = new String[] {"John", "Mary", "Bob"};

// #1
Arrays.asList(strArray).stream().forEach(s -> System.out.println(s));

// #2
Stream.of(strArray).forEach(System.out::println);

// #3
Arrays.stream(strArray).forEach(System.out::println);

/* output:
John
Mary
Bob
*/

In JDK1.8 you can use aggregate operations and a lambda expression:

String[] strArray = new String[] {"John", "Mary", "Bob"};

// #1
Arrays.asList(strArray).stream().forEach(s -> System.out.println(s));

// #2
Stream.of(strArray).forEach(System.out::println);

// #3
Arrays.stream(strArray).forEach(System.out::println);

/* output:
John
Mary
Bob
*/
那片花海 2025-02-16 08:38:49

arrays.toString

作为直接答案,由几个提供的解决方案,包括@esko ,使用 阵列。 toString arrays.deeptoString 方法是最好的。

Java 8- stream.collect(joining()),stream。

下面我尝试列出建议的其他一些方法,试图改进一点,最值得注意的是使用

int[] ints = new int[] {1, 2, 3, 4, 5};
System.out.println(IntStream.of(ints).mapToObj(Integer::toString).collect(Collectors.joining(", ")));
System.out.println(IntStream.of(ints).boxed().map(Object::toString).collect(Collectors.joining(", ")));
System.out.println(Arrays.toString(ints));

String[] strs = new String[] {"John", "Mary", "Bob"};
System.out.println(Stream.of(strs).collect(Collectors.joining(", ")));
System.out.println(String.join(", ", strs));
System.out.println(Arrays.toString(strs));

DayOfWeek [] days = { FRIDAY, MONDAY, TUESDAY };
System.out.println(Stream.of(days).map(Object::toString).collect(Collectors.joining(", ")));
System.out.println(Arrays.toString(days));

// These options are not the same as each item is printed on a new line:
IntStream.of(ints).forEach(System.out::println);
Stream.of(strs).forEach(System.out::println);
Stream.of(days).forEach(System.out::println);

Arrays.toString

As a direct answer, the solution provided by several, including @Esko, using the Arrays.toString and Arrays.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 a joining Collector, to mimic what the String.join is doing.

int[] ints = new int[] {1, 2, 3, 4, 5};
System.out.println(IntStream.of(ints).mapToObj(Integer::toString).collect(Collectors.joining(", ")));
System.out.println(IntStream.of(ints).boxed().map(Object::toString).collect(Collectors.joining(", ")));
System.out.println(Arrays.toString(ints));

String[] strs = new String[] {"John", "Mary", "Bob"};
System.out.println(Stream.of(strs).collect(Collectors.joining(", ")));
System.out.println(String.join(", ", strs));
System.out.println(Arrays.toString(strs));

DayOfWeek [] days = { FRIDAY, MONDAY, TUESDAY };
System.out.println(Stream.of(days).map(Object::toString).collect(Collectors.joining(", ")));
System.out.println(Arrays.toString(days));

// These options are not the same as each item is printed on a new line:
IntStream.of(ints).forEach(System.out::println);
Stream.of(strs).forEach(System.out::println);
Stream.of(days).forEach(System.out::println);
£噩梦荏苒 2025-02-16 08:38:49

从Java 8开始,也可以利用 join()方法,由 string class 在没有括号的情况下打印出数组元素,而没有括号,并由选择的定界符(这是下面显示的示例的空间字符):

String[] greeting = {"Hey", "there", "amigo!"};
String delimiter = " ";
String.join(delimiter, greeting) 

输出将是“嘿,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):

String[] greeting = {"Hey", "there", "amigo!"};
String delimiter = " ";
String.join(delimiter, greeting) 

The output will be "Hey there amigo!".

混浊又暗下来 2025-02-16 08:38:49

在Java 8之前,

我们可以使用 arrays.toString(array)打印一个维数组和 arrays.deeptostring(array)用于多维数组。

Java 8

现在我们可以选择 stream lambda 打印数组。

打印一维数组:

public static void main(String[] args) {
    int[] intArray = new int[] {1, 2, 3, 4, 5};
    String[] strArray = new String[] {"John", "Mary", "Bob"};

    //Prior to Java 8
    System.out.println(Arrays.toString(intArray));
    System.out.println(Arrays.toString(strArray));

    // In Java 8 we have lambda expressions
    Arrays.stream(intArray).forEach(System.out::println);
    Arrays.stream(strArray).forEach(System.out::println);
}

输出为:

[1,2,3,4,5]
[约翰,玛丽,鲍勃]
1
2
3
4
5
约翰
玛丽
鲍勃

打印多维阵列
以防万一我们要打印多维数组,我们可以使用 arrays.deeptostring(array) as:

public static void main(String[] args) {
    int[][] int2DArray = new int[][] { {11, 12}, { 21, 22}, {31, 32, 33} };
    String[][] str2DArray = new String[][]{ {"John", "Bravo"} , {"Mary", "Lee"}, {"Bob", "Johnson"} };

    //Prior to Java 8
    System.out.println(Arrays.deepToString(int2DArray));
    System.out.println(Arrays.deepToString(str2DArray));

    // In Java 8 we have lambda expressions
    Arrays.stream(int2DArray).flatMapToInt(x -> Arrays.stream(x)).forEach(System.out::println);
    Arrays.stream(str2DArray).flatMap(x -> Arrays.stream(x)).forEach(System.out::println);
} 

现在要观察到的要点是方法 arrays.stream.stream(t [])< /code>,如果是 int [] 返回我们 stream&lt; int []&gt; ,然后方法 flatmaptoint()映射每个元素通过将提供的映射函数应用于每个元素而产生的映射流的内容。

输出是:

[[[11,12],[21,22],[31,32,33]]
[[John,Bravo],[Mary,Lee],[Bob,Johnson]]
11
12
21
22
31
32
33
约翰
Bravo
玛丽

鲍勃
约翰逊

Prior to Java 8

We could have used Arrays.toString(array) to print one dimensional array and Arrays.deepToString(array) for multi-dimensional arrays.

Java 8

Now we have got the option of Stream and lambda to print the array.

Printing One dimensional Array:

public static void main(String[] args) {
    int[] intArray = new int[] {1, 2, 3, 4, 5};
    String[] strArray = new String[] {"John", "Mary", "Bob"};

    //Prior to Java 8
    System.out.println(Arrays.toString(intArray));
    System.out.println(Arrays.toString(strArray));

    // In Java 8 we have lambda expressions
    Arrays.stream(intArray).forEach(System.out::println);
    Arrays.stream(strArray).forEach(System.out::println);
}

The output is:

[1, 2, 3, 4, 5]
[John, Mary, Bob]
1
2
3
4
5
John
Mary
Bob

Printing Multi-dimensional Array
Just in case we want to print multi-dimensional array we can use Arrays.deepToString(array) as:

public static void main(String[] args) {
    int[][] int2DArray = new int[][] { {11, 12}, { 21, 22}, {31, 32, 33} };
    String[][] str2DArray = new String[][]{ {"John", "Bravo"} , {"Mary", "Lee"}, {"Bob", "Johnson"} };

    //Prior to Java 8
    System.out.println(Arrays.deepToString(int2DArray));
    System.out.println(Arrays.deepToString(str2DArray));

    // In Java 8 we have lambda expressions
    Arrays.stream(int2DArray).flatMapToInt(x -> Arrays.stream(x)).forEach(System.out::println);
    Arrays.stream(str2DArray).flatMap(x -> Arrays.stream(x)).forEach(System.out::println);
} 

Now the point to observe is that the method Arrays.stream(T[]), which in case of int[] returns us Stream<int[]> and then method flatMapToInt() 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:

[[11, 12], [21, 22], [31, 32, 33]]
[[John, Bravo], [Mary, Lee], [Bob, Johnson]]
11
12
21
22
31
32
33
John
Bravo
Mary
Lee
Bob
Johnson

下壹個目標 2025-02-16 08:38:49

如果您使用的是Java 1.4,则可以做:(

System.out.println(Arrays.asList(array));

当然,这也可以以1.5+起作用。)

If you're using Java 1.4, you can instead do:

System.out.println(Arrays.asList(array));

(This works in 1.5+ too, of course.)

违心° 2025-02-16 08:38:49

arrays.deeptostring(arr)仅在一行上打印。

int[][] table = new int[2][2];

要实际获取一个表作为二维表打印的表,我必须这样做:

System.out.println(Arrays.deepToString(table).replaceAll("],", "]," + System.getProperty("line.separator")));

似乎 arrays.deeptostring(arr)方法应该采用一个分隔符字符串,但不幸的是不是。

Arrays.deepToString(arr) only prints on one line.

int[][] table = new int[2][2];

To actually get a table to print as a two dimensional table, I had to do this:

System.out.println(Arrays.deepToString(table).replaceAll("],", "]," + System.getProperty("line.separator")));

It seems like the Arrays.deepToString(arr) method should take a separator string, but unfortunately it doesn't.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文