Extend Object[] for generic type

foxtrot9 :

I am trying to define a generic method which can print array of object type. I have written following code:

class ArrayPrinter
{
    public <T extends Object[]> void printArray(T t) {
        for(Object o: t) {
            System.out.println(o);
        }
    }  
}
public class javaGenerics {
    public static void main(String args[]) {
        ArrayPrinter myArrayPrinter = new ArrayPrinter();
        Integer[] intArray = {1, 2, 3};
        String[] stringArray = {"Hello", "World"};
        myArrayPrinter.printArray(intArray);
        myArrayPrinter.printArray(stringArray); 
    }
}

But it is not working and is throwing following error:

javaGenerics.java:7: error: unexpected type
    public <T extends Object[]> void printArray(T t) {
                            ^
  required: class
  found:    Object[]
1 error

I can understand from error that I provide a class name. But I don't know what would be the class name for array of objects.

Joakim Danielson :

I would change printArray to

public <T extends Object> void printArray(T[] t) {
    for(Object o: t) {
        System.out.println(o);
    }
}  

That is let T extend Object rather than an Object array and make t an array of T.

Actually it is not necessary to extend Object at all since the type parameter is always a non-primitive type

public <T> void printArray(T[] t) {
    for(Object o: t) {
        System.out.println(o);
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=310722&siteId=1