generic method to print all elements in an array
private static void printArray(Object arr) {
// TODO Auto-generated method stub
String arrayClassName=arr.getClass().getSimpleName();
if (arrayClassName.equals("int[]"))
System.out.println(java.util.Arrays.toString((int[]) arr));
if (arrayClassName.equals("char[]"))
System.out.println(java.util.Arrays.toString((char[]) arr));
}
java.util.Arrays.toString(array)
should do.
- commons-lang also have that -
ArrayUtils.toString(array)
(but prefer the JDK one) - commons-lang allows for custom separator -
StringUtils.join(array, ',')
- guava also allows a separator, and has the option to skip null values:
Joiner.on(',').skipNulls().join(array)
All of these return a String
, which you can then System.out.println(..)
or logger.debug(..)
. Note that these will give you meaningful input if the elements of the array have implemented toString()
in a meaningful way.
The last two options, alas, don't have support for primitive arrays, but are nice options to know.
You cant write a generic definition for primitive arrays. Instead, you can use method overloading and write a method for each primitive array type like this,
public static void printArray(int[] arr)
public static void printArray(short[] arr)
public static void printArray(long[] arr)
public static void printArray(double[] arr)
public static void printArray(float[] arr)
public static void printArray(char[] arr)
public static void printArray(byte[] arr)
public static void printArray(boolean[] arr)