I wanna a method that would loop any type array and print them, I have written the following:
public static <T> void printArray(T[] arr){
for(T t: arr){
System.out.print(t+" ");
}
System.out.println("");
}
but this one only works for class arrays, what if I have a char[]
instead of a Character[]
, or a int[]
instead of an Integer[]
, or is there a way to cast them before hand? Thanks
In order to print an integer array, all you need to do is call Arrays. toString(int array) method and pass your integer array to it. This method will take care of the printing content of your integer array, as shown below. If you directly pass int array to System.
To understand the reason, you first need to know two arrays are covariant and generics are invariant. Because of this fundamental reason, arrays and generics do not fit well with each other.
Print Array in One Line with Java StreamsArrays. toString() and Arrays. toDeepString() just print the contents in a fixed manner and were added as convenience methods that remove the need for you to create a manual for loop.
java.util.Arrays.toString(array)
should do.
ArrayUtils.toString(array)
(but prefer the JDK one)StringUtils.join(array, ',')
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With