0

I want to write a generic method that prints an array of any type that I send to it. I tried

public static <T> void printArr(T[] a)
{
    int length = a.length;
    for(int i = 0; i < length; i++)
    {
    System.out.print(a[i] + " ");
    }       
}

But when I try to use an array of ints it gives me an error saying "change method 'printArr(T[]) ' to 'printArr(int[])'. It works when its a normal method. Anyone know how to do this?

  • 1
    Generics do not work with primitive types. – Matt Ball Sep 24 '14 at 23:07
  • 1
    Generic type (in your case ``) can only represent classes like `Object`, `String`, and so on, not primitives like `int`, `long`... – Pshemo Sep 24 '14 at 23:10
  • By the way, generics is unnecessary here. It would be the same to just declare your method `public static void printArr(Object[] a)` – newacct Sep 25 '14 at 01:49

4 Answers4

0

I guess you are using the primitive type int but here, an array of Objects is expected so you must use the wrapper Integer :

print(new Integer[] { 1,2,3,4 });
Dici
  • 25,226
  • 7
  • 41
  • 82
0

With Java's generics, a generic type parameter must stand for an actual object type and not a primitive type. Therefore, you can't pass an int[] (or any other array of a primitive type) to a method expecting a generic array.

You can create an array of the wrapper type Integer[] (or copy an existing int[] to an Integer[]) and pass that in to printArr, or you can overload printArr to accept an int[].

rgettman
  • 176,041
  • 30
  • 275
  • 357
0

Pretty certain that you can't use ints because any method that uses generics must be able to be cast to an Object, which int is not (it's a primitive). If you were to provide an array of Integers I believe it would work just fine.

Why don't Java Generics support primitive types?

Community
  • 1
  • 1
mattforni
  • 855
  • 5
  • 11
0

Have a look at how the equivalent function Arrays.toString()(JavaDoc) is implemented. It's one function that will take an Object[] for example an Integer[], and one for each kind of primitive-array like int[]. Here's the code for the Object[] and the int[] version:

Object[]:

public static String toString(Object[] a) {
    if (a == null)
        return "null";

    int iMax = a.length - 1;
    if (iMax == -1)
        return "[]";

    StringBuilder b = new StringBuilder();
    b.append('[');
    for (int i = 0; ; i++) {
        b.append(String.valueOf(a[i]));
        if (i == iMax)
            return b.append(']').toString();
        b.append(", ");
    }
}

int[]:

public static String toString(int[] a) {
    if (a == null)
        return "null";
    int iMax = a.length - 1;
    if (iMax == -1)
        return "[]";

    StringBuilder b = new StringBuilder();
    b.append('[');
    for (int i = 0; ; i++) {
        b.append(a[i]);
        if (i == iMax)
            return b.append(']').toString();
        b.append(", ");
    }
}

There's a lot to learn from this code. For example it's not using Generics in any way.

If you actually wanted to make a method that could take any array it would probably have to take an Object, which you could then check the class of, and invoke the appropriate Arrays.toString()(or generate a string manually). Probably not a good idea, however. We have overloading for a reason.

Edit: Just for fun, here is such a method that will take any array. Actually, any Object at all.

public static void printAny(Object arr) {
    Class<?> cl = arr.getClass();
    if (cl.isArray()) {
        Class<?> type = cl.getComponentType();
        if (!type.isPrimitive()) {
            System.out.println(Arrays.toString((Object[]) arr));
        } else {
            switch (type.toString()) {
                case "int":
                    System.out.println(Arrays.toString((int[]) arr));
                    break;
            }
        }
    } else {
        System.out.println(arr);
    }
}
Erik Vesteraas
  • 4,675
  • 2
  • 24
  • 37