I am trying to understand generics. In the below code getDuplicate() return type PlaceHolder<X,X>
has same parameter X which compiles fine. But when I use the same parameter type in MyClass<T,T>
it says "type variable T already defined". Can someone explain how it's possible with getDuplicate method?
class PlaceHolder<K,V> {
public K k;
public K v;
public PlaceHolder(K k, K v){
this.k = k;
this.v = v;
}
public K get(){ return k; }
public static <X> PlaceHolder<X,X> getDuplicateHolder(X x){
return new PlaceHolder<X,X>(x,x);
}
}
class MyTest<T,T> {}
The difference is that
X
is declared once and used twice whereT
is being declared twice.In methods, you can declare type parameters with
<>
after modifiers but before the return type. Likewise, in classes and interfaces, you can declare type parameters after the class name but before anyimplements
and/orextends
clauses and before the class/interface body.You may use these type parameters in the scope in which they're declared. Declaring a return type of
PlaceHolder<X, X>
is usingX
twice, but declaring a classMyText<T, T>
is attempting to declareT
twice.A variable-equivalent analogy would be declaring a variable and using it twice:
vs. attempting to declare two variables with the same name.
You just need to make sure you know when you're declaring a type parameter and when you're using an existing type parameter.