ジェネリック型のオブジェクトを[]拡張

foxtrot9:

私は、オブジェクト型の配列を印刷することができ、一般的なメソッドを定義しようとしています。私は、コードを次のよう書かれています:

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); 
    }
}

しかし、それは動作していないと、次のエラーを投げています。

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

私は、クラス名を提供することをエラーから理解することができます。しかし、私は、オブジェクトの配列のためのクラス名になるのか分かりません。

ヨアキムダニエルソン:

私はにプリントアレイを変更します

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

TはなくObject配列より物体を拡張し、TをTのアレイを作るせされていること

typeパラメータは、常に非プリミティブ型であるため、実際には、すべてのオブジェクトを拡張する必要はありません

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

おすすめ

転載: http://43.154.161.224:23101/article/api/json?id=316681&siteId=1