17

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

user685275
  • 1,867
  • 7
  • 24
  • 32
  • What about t.toString() instead of t+ – Preston May 02 '11 at 20:08
  • 2
    Unfortunately array.toString() just calls Object.toString() and you get something like `[C@e6f8730` I suggested to the JDK 7 coin project lead he fix this but I didn't sell it to him. ;) – Peter Lawrey May 02 '11 at 20:13
  • @Peter Lawrey good suggestion. What was their argument against it? That everyone can make great use of that hash value? – Bozho May 02 '11 at 20:21
  • They said you can use Arrays.toString/equals/hashCode to do what you want. I pointed out that Sun/Oracle supply 9 different helper classes for arrays including Array/Arrays/ArrayUtils in various packages and its a mess that someone new to Java shouldn't need to have to learn. (not to mention Apache commons and Guava) In fact you can hack/extend Object to fix toString() etc and the Idea/compilers accept it but its an ugly hack. So IMHO its not that big a change as you won't have to change the JVM or IDEs to make it work. – Peter Lawrey May 02 '11 at 20:27
  • I heard Joshua Bloch looked at this, and I heard he felt that to do it really properly was just too complicated. – Peter Lawrey May 02 '11 at 20:28
  • by the way, generics is not needed in your code above: `public static void printArray(Object[] arr){ for(Object t: arr){ ...` – newacct May 04 '11 at 06:40

4 Answers4

26

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.

Bozho
  • 554,002
  • 136
  • 1,025
  • 1,121
  • Guava's Joiner only works for *object* arrays. For primitive arrays, you have the join() method in com.google.common.primitives (e.g. Chars.join() : http://guava-libraries.googlecode.com/svn/trunk/javadoc/com/google/common/primitives/Chars.html ) – Etienne Neveu May 02 '11 at 20:21
  • @eneveu that's in my last paragraph ;) – Bozho May 02 '11 at 20:23
  • @Bozho: yes, but I also wanted to link to the join methods for primitive types, since this was what the questioner seemed to be after ;) It was not a critic, merely a suggestion to add this to your answer. – Etienne Neveu May 03 '11 at 14:09
  • still, any particular call of `java.util.Arrays.toString()` does not work on "any type of array", as the OP wants. it can only work on Object[] or int[] or double[], etc. you will still need to separate out all the cases in order to work on any type of array – newacct May 04 '11 at 06:38
  • @newacct it works through overloading, yes. But if you have a primitive array, you know its type at compile time. – Bozho May 04 '11 at 06:42
  • @Bozho: not necessarily. I could have an `Object` and it could be a primitive array or reference array – newacct Aug 31 '11 at 03:30
  • In commons-lang3 (and perhaps also in commons-lang), the ArrayUtils.toString() method has one striking advantage in some situations, as that it is capable of printing multi-dimensional arrays properly. The built-in version would just print the inner array's toString() values, not the actual contents. – khituras Oct 06 '15 at 09:39
2

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)
Aravindan R
  • 3,066
  • 1
  • 26
  • 42
1
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));
    }
Pradeep C
  • 21
  • 3
0

You can't pass primitive arrays to the printArray() method

Kal
  • 23,894
  • 7
  • 58
  • 61