views:

17724

answers:

4

What's the simplest way of printing an array of primitives or of objects in Java? Here are some example inputs and outputs:

int[] intArray = new int[] {1, 2, 3, 4, 5};
//output: [1, 2, 3, 4, 5]

String[] strArray = new String[] {"John", "Mary", "Bob"};
//output: [John, Mary, Bob]
+41  A: 

In Java 5 Arrays.toString(arr) or Arrays.deepToString(arr) for arrays within arrays. Note that Object[] version calls .toString() of each object in array. If my memory serves me correct, the output is even decorated in the exact way you're asking.

Esko
Yep - this is the best way to go. +1
Yuval A
Thanks, I thought there was a compact solution but just couldn't find it. Hopefully this will come up next time I search Google :)
Alex Spurling
I did actually check before posting that does Google find that info easily: It didn't since Google has a preference for Java 1.4.2 apidocs for some reason and like I said, this is in Java 5.
Esko
+7  A: 

Always check the standard libraries first. Try:

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

or if your array contains other arrays as elements:

System.out.println(Arrays.deepToString(array));
Limbic System
+4  A: 

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

Ross
Unfortunately this only works with arrays of objects, not arrays of primitives.
Alex Spurling
+1  A: 

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.

This works great. Thanks!!!

import java.util.Arrays;
.
.
.
System.out.println( Arrays.toString( myarray ) );
Russ Bateman
+1 - Thanks for showing the import.
Clinton Blackmore