The easy way to do this is just use Arrays.toString
public static void printArray(int[] myArray)
{
System.out.print( Arrays.toString( myArray ) );
}
Note this prints brackets instead of braces. In the interest of completeness, if you do implement this yourself, don't forget to check for the array being null
in addition to other boundary conditions like length = 0.
Here is an example using StringBuilder
, where I just always remove the last two characters after checking for null
and length = 0. If you have a very complicated string to calculate for each item in a list/array, this can be easier than copying the code to make each item outside the loop, and can be slightly faster than checking for i==array.length-1
each time through the loop.
public class MyArraysToString
{
public static void main( String[] args )
{
int[] test = { 8, 7, 6, 5, 4, };
printArray( test );
System.out.println( myToString( null ) );
System.out.println( myToString( new int[0] ) );
System.out.println( myToString( test ) );
}
public static void printArray( int[] myArray )
{
System.out.println( Arrays.toString( myArray ) );
}
public static String myToString( int[] a ) {
if( a == null ) return "null";
if( a.length == 0 ) return "{}";
StringBuilder sb = new StringBuilder();
sb.append( '{' );
for (int i = 0; i < a.length; i++) {
sb.append( a[i] );
sb.append( ", " );
}
sb.setLength( sb.length()-2 );
sb.append( '}' );
return sb.toString();
}
}