This article is participating in the Java Theme Month – Java Debug Notes Event, see the event link for details
Question: How to print an array in the simplest way?
Because there is no toString() method in Java arrays, I would only get its memory address if I called the array toStrign() method directly. Like this, it’s dehumanizing:
int[] intArray = new int[] {1, 2, 3, 4, 5}; System.out.println(intArray); // sometimes output '[I@3343c8b3'Copy the code
So what’s the easiest way to output an array? What I want is this:
Int [] intArray = new int[] {1, 2, 3, 4, 5}; Output: [1, 2, 3, 4, 5]Copy the code
String[] strArray = new String[] {"John", "Mary", "Bob"}; Output: [John, Mary, Bob]Copy the code
Answer 1:
Use arrays.tostring (arr) or arrays.deepToString (arr) to print Arrays in Java 5+ above. Note that the Object[] version calls.toString() for each Object in the array. The output is even decorated the way you want it to be.
🌰 Here are some chestnuts:
Simple array
String[] array = new String[] {"John", "Mary", "Bob"};
System.out.println(Arrays.toString(array));
Copy the code
Output:
[John, Mary, Bob]
Copy the code
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));
Copy the code
Output:
[[John, Mary], [Alice, Bob]]
Copy the code
A double array
Double [] doubleArray = {7.0, 9.0, 5.0, 1.0, 3.0}; System.out.println(Arrays.toString(doubleArray));Copy the code
Output:
[7.0, 9.0, 5.0, 1.0, 3.0]Copy the code
An array of int
int[] intArray = { 7, 9, 5, 1, 3 };
System.out.println(Arrays.toString(intArray));
Copy the code
Output:
[7, 9, 5, 1, 3]Copy the code
Answer 2:
Always check the introduction of the library first
import java.util.Arrays;
Copy the code
Then try to output:
System.out.println(Arrays.toString(array));
Copy the code
Or if your array contains other arrays as elements:
System.out.println(Arrays.deepToString(array));
Copy the code
provenance
Stack Overflow :What’s the Simplest Way to Print a Java Array?