Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

generic method to print all elements in an array

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

like image 404
user685275 Avatar asked May 02 '11 20:05

user685275


People also ask

How do I print all elements in an array?

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.

Can you use generics with an array?

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.

How do I print all elements in an array in one line?

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.


2 Answers

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.

like image 84
Bozho Avatar answered Oct 18 '22 23:10

Bozho


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)
like image 2
Aravindan R Avatar answered Oct 19 '22 00:10

Aravindan R