7

Java 7 で Eclipse 4.2 を使用し、List インターフェイスの次のメソッドを実装しようとすると、警告が表示されました。

public <T> T[] toArray(T[] a) {
    return a;

}

警告には次のように書かれています:

型パラメーター T は型 T を隠しています

スクリーンショット

なんで ?どうすればそれを取り除くことができますか?

4

2 に答える 2

13

Listインターフェイスも汎用です。クラスのジェネリック型にもTを使用していないことを確認してください。http://docs.oracle.com/javase/6/docs/api/java/util/List.htmlでは、クラスのジェネリックパラメータに「E」を使用し、toArray()のジェネリックパラメータに「T」を使用していることに注意してください。 。これにより、オーバーラップが防止されます。

public class MyList<T> implements List<T> {

// V1 (compiler warning)
public <T> T[] toArray(T[] array) {
    // in this method T refers to the generic parameter of the generic method
    // rather than to the generic parameter of the class. Thus we get a warning.
    T variable = null; // refers to the element type of the array, which may not be the element type of MyList
} 

// V2 (no warning)
public <T2> T2[] toArray(T2[] array) {
    T variable = null; // refers to the element type of MyList
    T2 variable2 = null; // refers to the element type of the array
}

}

于 2012-09-22T22:30:43.823 に答える