简体   繁体   English

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

[英]What's the simplest way to print a Java array?

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() :在 Java 和 arrays 中,不要覆盖toString() ,因此如果您尝试直接打印一个,您将得到className + '@' + 数组hashCode的十六进制,如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] .但通常,我们实际上想要更像[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]

Since Java 5 you can use Arrays.toString(arr) or Arrays.deepToString(arr) for arrays within arrays.从 Java 5 开始,您可以将Arrays.toString(arr)Arrays.deepToString(arr)用于数组中的数组。 Note that the Object[] version calls .toString() on each object in the array.请注意, Object[]版本对数组中的每个对象调用.toString() 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"}}; System.out.println(Arrays.toString(deepArray)); //output: [[Ljava.lang.String;@106d69c, [Ljava.lang.String;@52e922] System.out.println(Arrays.deepToString(deepArray));

    Output:输出:

     [[John, Mary], [Alice, Bob]]
  • double Array: double数组:

     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数组:

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

    Output:输出:

     [7, 9, 5, 1, 3 ]

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));

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 )很高兴知道,但是,至于“总是先检查标准库”,我永远不会偶然发现Arrays.toString( myarray )的技巧

--since I was concentrating on the type of myarray to see how to do this. --因为我专注于 myarray 的类型以了解如何执行此操作。 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.我不想遍历这件事:我想要一个简单的调用来使它类似于我在 Eclipse 调试器中看到的那样,而 myarray.toString() 只是没有这样做。

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

In JDK1.8 you can use aggregate operations and a lambda expression:在 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
*/

Arrays.toString数组.toString

As a direct answer, the solution provided by several, including @Esko , using the Arrays.toString and Arrays.deepToString methods, is simply the best.作为直接答案,包括 @Esko 在内的几个使用Arrays.toStringArrays.deepToString方法提供的解决方案简直是最好的。

Java 8 - Stream.collect(joining()), Stream.forEach 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.下面我尝试列出一些其他建议的方法,尝试进行一些改进,其中最值得注意的添加是使用Stream.collect运算符,使用joining Collector来模仿String.join正在做的事情。

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);

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):从 Java 8 开始,还可以利用String 类提供的join()方法打印出不带括号的数组元素,并由选择的分隔符分隔(这是下面示例中的空格字符) :

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

The output will be "Hey there amigo!".输出将是“嘿,朋友!”。

Prior to Java 8在 Java 8 之前

We could have used Arrays.toString(array) to print one dimensional array and Arrays.deepToString(array) for multi-dimensional arrays.我们可以使用Arrays.toString(array)打印一维数组,使用Arrays.deepToString(array) (array) 打印多维数组。

Java 8爪哇 8

Now we have got the option of Stream and lambda to print the array.现在我们可以选择Streamlambda来打印数组。

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] [1、2、3、4、5]
[John, Mary, Bob] [约翰、玛丽、鲍勃]
1 1
2 2
3 3
4 4
5 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:打印多维数组如果我们想打印多维数组,我们可以使用Arrays.deepToString(array)作为:

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.现在要注意的是方法Arrays.stream(T[]) ,在int[]的情况下返回Stream<int[]>然后方法flatMapToInt()将流的每个元素映射到映射的内容通过将提供的映射函数应用于每个元素而生成的流。

The output is:输出是:

[[11, 12], [21, 22], [31, 32, 33]] [[11, 12], [21, 22], [31, 32, 33]]
[[John, Bravo], [Mary, Lee], [Bob, Johnson]] [[约翰,布拉沃],[玛丽,李],[鲍勃,约翰逊]]
11 11
12 12
21 21
22 22
31 31
32 32
33 33
John约翰
Bravo布拉沃
Mary玛丽
Lee
Bob鲍勃
Johnson约翰逊

If you're using Java 1.4, you can instead do:如果您使用的是 Java 1.4,则可以改为:

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

(This works in 1.5+ too, of course.) (当然,这也适用于 1.5+。)

Arrays.deepToString(arr) only prints on one line. Arrays.deepToString(arr)只打印一行。

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.似乎Arrays.deepToString(arr)方法应该采用分隔符字符串,但不幸的是它没有。

for(int n: someArray) {
    System.out.println(n+" ");
}

Different Ways to Print Arrays in Java:在 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()使用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]]输出:[[Ljava.lang.String;@1ad086a [[Ljava.lang.String;@10385c1, [Ljava.lang.String;@42719c] [[第五、第六]、[第七、第八]]

Resource: Access An Array资源: 访问数组

Using regular for loop is the simplest way of printing array in my opinion.在我看来,使用常规for循环是打印数组的最简单方法。 Here you have a sample code based on your intArray在这里,您有一个基于您的 intArray 的示例代码

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

It gives output as yours 1, 2, 3, 4, 5它提供您的输出 1, 2, 3, 4, 5

It should always work whichever JDK version you use:它应该始终适用于您使用的任何 JDK 版本:

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

It will work if the Array contains Objects.如果Array包含对象,它将起作用。 If the Array contains primitive types, you can use wrapper classes instead storing the primitive directly as..如果Array包含原始类型,则可以使用包装类而不是将原始类型直接存储为..

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.它是由称为自动装箱的java的性质发生的。

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
} 

I came across this post in Vanilla #Java recently.我最近在Vanilla #Java中看到了这篇文章。 It's not very convenient writing Arrays.toString(arr);Arrays.toString(arr);不是很方便, then importing java.util.Arrays; , 然后导入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.直接打印一个数组会给出内部表示和 hashCode。 Now, all classes have Object as the parent-type.现在,所有类都将Object作为父类型。 So, why not hack the Object.toString() ?那么,为什么不破解Object.toString()呢? Without modification, the Object class looks like this:未经修改,Object 类如下所示:

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 .这个修改后的类可以通过在命令行中添加以下内容来简单地添加到类路径中: -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.现在,随着自 Java 5 以来deepToString(..)的可用性, toString(..)可以轻松更改为deepToString(..)以添加对包含其他数组的数组的支持。

I found this to be a quite useful hack and it would be great if Java could simply add this.我发现这是一个非常有用的 hack,如果 Java 可以简单地添加它,那就太好了。 I understand potential issues with having very large arrays since the string representations could be problematic.我理解拥有非常大的数组的潜在问题,因为字符串表示可能有问题。 Maybe pass something like a System.out or a PrintWriter for such eventualities.可能会为此类事件传递诸如System.outPrintWriter之类的东西。

In java 8 it is easy.在 java 8 中,这很容易。 there are two keywords有两个关键字

  1. stream: Arrays.stream(intArray).forEach流: Arrays.stream(intArray).forEach
  2. method reference: ::println方法参考::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 ie如果要在同一行中打印数组中的所有元素,则只需使用print而不是println

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));

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

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);
     }

There's one additional way if your array is of type char[]:如果您的数组是 char[] 类型,还有另一种方法:

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

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

prints印刷

abc

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这种方法不需要循环,最好只用于小型阵列

Using org.apache.commons.lang3.StringUtils.join(*) methods can be an option可以选择使用 org.apache.commons.lang3.StringUtils.join(*) 方法
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>

For-each loop can also be used to print elements of array: For-each 循环也可用于打印数组元素:

int array[] = {1, 2, 3, 4, 5};
for (int i:array)
    System.out.println(i);
  • It is very simple way to print array without using any loop in JAVA.在 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() -> 所以,这个二维数组不能用 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]]

☻♥ Done Keep Code ☻♥完成保留代码

To add to all the answers, printing the object as a JSON string is also an option.要添加到所有答案,也可以选择将对象打印为 JSON 字符串。

Using Jackson:使用杰克逊:

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

Using Gson:使用 Gson:

Gson gson = new Gson();
System.out.println(gson.toJson(anyArray));
// 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]

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例如,如果 main 是这样的

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

the output will be { [1] [2] [3] [4] }输出将是 { [1] [2] [3] [4] }

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);
        }
      }
    }

This is marked as a duplicate for printing a byte[] .这被标记为重复打印 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.如果它包含 ISO-8859-1 字符,则可以将其打印为字符串。

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或者如果它包含一个 UTF-8 字符串

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.或者如果您想将其打印为 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.

if you are running jdk 8.如果您正在运行 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]

If you are using Java 11如果您使用的是 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

在 Java 8 中:

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

If using Commons.Lang library<\/a> , we could do:如果使用Commons.Lang 库<\/a>,我们可以这样做:

ArrayUtils.toString(array)<\/code>

int[] intArray = new int[] {1, 2, 3, 4, 5};
String[] strArray = new String[] {"John", "Mary", "Bob"};
ArrayUtils.toString(intArray);
ArrayUtils.toString(strArray);

In JDK1.8 you can use aggregate operations and a lambda expression:在 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
*/

There are several ways to print an array elements.First of all, I'll explain that, what is an array?..Array is a simple data structure for storing data..When you define an array , Allocate set of ancillary memory blocks in RAM.Those memory blocks are taken one unit .. 有几种打印数组元素的方法。首先,我将解释什么是数组?.Array是用于存储数据的简单数据结构。.当您定义数组时,分配一组辅助存储块在RAM中。这些存储块被当作一个单元..

Ok, I'll create an array like this, 好的,我将创建一个这样的数组,

class demo{
      public static void main(String a[]){

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

           System.out.print(number);
      }
}

Now look at the output, 现在看一下输出

在此处输入图片说明

You can see an unknown string printed..As I mentioned before, the memory address whose array(number array) declared is printed.If you want to display elements in the array, you can use "for loop " , like this.. 您可以看到打印了一个未知的字符串。如前所述,已打印声明了array(number array)的内存地址。如果要显示数组中的元素,可以使用“ for loop”,如下所示。

class demo{
      public static void main(String a[]){

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

           int i;

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

Now look at the output, 现在看一下输出

在此处输入图片说明

Ok,Successfully printed elements of one dimension array..Now I am going to consider two dimension array..I'll declare two dimension array as "number2" and print the elements using "Arrays.deepToString()" keyword.Before using that You will have to import 'java.util.Arrays' library. 好,成功打印一维数组的元素。.现在我将考虑二维数组。.我将二维数组声明为“ number2”,并使用“ Arrays.deepToString()”关键字打印元素。您将必须导入“ java.util.Arrays”库。

 import java.util.Arrays;

 class demo{
      public static void main(String a[]){

           int[][] number2={{1,2},{3,4},{5,6}};`

           System.out.print(Arrays.deepToString(number2));
      }
}

consider the output, 考虑输出,

在此处输入图片说明

At the same time , Using two for loops ,2D elements can be printed..Thank you ! 同时,使用两个for循环,可以打印2D元素。谢谢!

toString is a way to convert an array to string. toString是一种将数组转换为字符串的方法。

Also, you can use: 另外,您可以使用:

for (int i = 0; i < myArray.length; i++){
System.out.println(myArray[i] + " ");
}

This for loop will enable you to print each value of your array in order. 这个for循环将使您能够按顺序打印数组的每个值。

By using the java.util.Arrays:通过使用 java.util.Arrays:

String mRole = "M_XXX_ABC";        
System.out.println(Arrays.asList(mRole.split("_")).toString());

output: [M, XXX, ABC]输出:[M, XXX, ABC]

Java array is a data structure where we can store the elements of the same data type. Java 数组是一种数据结构,我们可以在其中存储相同数据类型的元素。 The elements of an array are stored in a contiguous memory location.数组的元素存储在连续的内存位置。 So, we can store a fixed set of elements in an array.因此,我们可以在数组中存储一组固定的元素。

In Java, arrays are objects.在 Java 中,数组是对象。 All methods of class object may be invoked in an array.类对象的所有方法都可以在数组中调用。 We can store a fixed number of elements in an array.我们可以在数组中存储固定数量的元素。

Example :例子 :

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

output:输出:

[I@63961c42

Why did Java not print our array?为什么 Java 不打印我们的数组? What is happening under the hood?引擎盖下发生了什么?

The System.out.println() method converts the object we passed into a string by calling String.valueOf() . System.out.println() 方法通过调用 String.valueOf() 将我们传递的对象转换为字符串。 If we look at the String.valueOf() method's implementation, we'll see this:如果我们查看 String.valueOf() 方法的实现,我们会看到:

public static String valueOf(Object obj) {
return (obj == null) ? "null" : obj.toString();
}

If the passed-in object is null it returns null, else it calls obj.toString() .如果传入的对象为 null,则返回 null,否则调用 obj.toString() 。 Eventually, System.out.println() calls toString() to print the output.最后,System.out.println() 调用 toString() 来打印输出。

If that object's class does not override Object.toString()'s implementation, it will call the Object.toString() method.如果该对象的类没有覆盖 Object.toString() 的实现,它将调用 Object.toString() 方法。

Object.toString() returns getClass().getName()+'@'+Integer.toHexString(hashCode()) . Object.toString() 返回 getClass().getName()+'@'+Integer.toHexString(hashCode()) 。 In simple terms, it returns: “class name @ object's hash code”.简单来说,它返回:“类名@对象的哈希码”。

In our previous output [I@63961c42 , the [ states that this is an array, and I stands for int (the type of the array).在我们之前的输出 [I@63961c42 中,[ 表示这是一个数组,而 I 代表 int(数组的类型)。 63961c42 is the unsigned hexadecimal representation of the hash code of the array. 63961c42 是数组散列码的无符号十六进制表示。

Whenever we are creating our own custom classes, it is a best practice to override the Object.toString() method.每当我们创建自己的自定义类时,最佳做法是覆盖 Object.toString() 方法。

There are following ways to print an array in Java在Java中有以下几种打印数组的方法


for loop for循环

Java for loop is used to execute a set of statements repeatedly until a particular condition is satisfied. Java for 循环用于重复执行一组语句,直到满足特定条件。

In the following example, we have created an array of length three and initialized elements into it.在下面的示例中,我们创建了一个长度为 3 的数组并在其中初始化了元素。 We have used for loop for fetching the values from the array.我们已经使用 for 循环从数组中获取值。 It is the most popular way to print array in Java.它是 Java 中最流行的打印数组的方式。

    String[] strArray = new String[]{"John", "Mary", "Bob"};
    for (int i = 0; i < strArray.length; i++)    
        System.out.println(strArray[i]);

output:输出:

 John
 Mary
 Bob

for each对于每个

Java for-each loop is also used to traverse over an array or collection. Java for-each 循环也用于遍历数组或集合。 It works on the basis of elements.它基于元素工作。 It returns elements one by one in the defined variable.它在定义的变量中一一返回元素。

String[] strArray = new String[]{"John", "Mary", "Bob"};
    for (String str : strArray)
        System.out.println(str);

output:输出:

John
Mary
Bob

Arrays.toString() Arrays.toString()

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

output:输出:

[John, Mary, Bob]

According to your question above output is exact what you want根据您上面的问题,输出正是您想要的

Arrays.deepToString() {Off Topic} Arrays.deepToString() {离题}

The deepToString() method of Java Arrays class is designed for converting multidimensional arrays to strings. Java Arrays 类的 deepToString() 方法旨在将多维数组转换为字符串。

It accepts an array as a parameter.它接受一个数组作为参数。 It returns the String representation of an array.它返回数组的字符串表示形式。

In the following example, we have created a two dimensional array of Integer type.在下面的示例中,我们创建了一个 Integer 类型的二维数组。

 Integer[][] strArray = {{1, 2}, {3, 4}, {5}};
    System.out.println(Arrays.deepToString(strArray));

output:输出:

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

Arrays.asList() Arrays.asList()

Java Arrays.asList() is a static method of Java Arrays class which belongs to java.util package. Java Arrays.asList() 是Java Arrays 类的静态方法,属于java.util 包。 It act as a bridge between array based and collection based API.The method also provides an easy way to create a fixed-size list initialize to contain many elements.It accepts an array as an argument.它充当基于数组和基于集合的 API 之间的桥梁。该方法还提供了一种简单的方法来创建一个固定大小的列表初始化以包含许多元素。它接受一个数组作为参数。 It returns the list view of an array.它返回数组的列表视图。

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

output:输出:

[John, Mary, Bob]

Iterator interface迭代器接口

Iterator is an interface which belongs to java.util package. Iterator是一个属于 java.util 包的接口。 The Iterator object can be created by calling iterator() method. Iterator 对象可以通过调用 iterator() 方法来创建。 It is present in Collection interface.它存在于 Collection 界面中。 It returns an iterator.它返回一个迭代器。

 String[] strArray = new String[]{"John", "Mary", "Bob"};
    Iterator<String> it = Arrays.asList(strArray).iterator();
    while (it.hasNext())
        System.out.println(it.next());

output:输出:

John
Mary
Bob

Stream API流API

The Stream API is used to process collections of objects. Stream API 用于处理对象集合。 A stream is a sequence of objects.流是一个对象序列。 Streams don't change the original data structure, they only provide the result as per the requested operations.流不会改变原始数据结构,它们仅根据请求的操作提供结果。

There are two terminal operations which we can apply to a stream to print an array.我们可以将两个终端操作应用于流以打印数组。

Get an iterator to the stream获取流的迭代器

Iterator it=Arrays.stream(strArray).iterator();  

Using stream().forEach()使用 stream().forEach()

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

Use the Arrays class.使用 Arrays class。 It has multiple utility methods and its toString() is overriden to display array elements in a human readable way.它有多个实用方法,并且它的toString()被覆盖以以人类可读的方式显示数组元素。 Arrays.toString(arr)

If you want to print, evaluate Array content like that you can use Arrays.toString 如果要打印,请评估数组内容,就像可以使用Arrays.toString

jshell> String[] names = {"ram","shyam"};
names ==> String[2] { "ram", "shyam" }

jshell> Arrays.toString(names);
$2 ==> "[ram, shyam]"

jshell> 

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

相关问题 使用Java 8将String数组转换为int数组的最简单方法是什么? - What's the simplest way to convert a String Array to an int Array using Java 8? 在Java应用程序中响应AJAX请求的最简单方法是什么? - What's the simplest way to respond to AJAX requests within a Java application? 在Java中设置Web服务器的最简单方法是什么? - What's the simplest way to setup a web server in java? 将数据从 java 程序存储到 MySQL 的最简单方法是什么? - What's the simplest way to store data from a java program to MySQL? 为java程序制作本地遥控器的最简单方法是什么? - What's the simplest way to make a local remote for a java program? 将项目添加到 Java 数组开头的最简单方法是什么 - What is the simplest way to add an item to the beginning of a Java array 在 Java 中绘制最简单的方法是什么? - What is the simplest way to draw in Java? 在java中打印多维数组的最佳方法是什么? - What is the best way to print a multidimensional array in java? 使用 Java 从 Amazon S3 获取链接的最简单方法是什么? - What's the simplest way to get links from Amazon S3 using Java? 用Java编写文本文件的最简单方法是什么? - What is the simplest way to write a text file in Java?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM