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 where T
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 any implements
and/or extends
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 using X
twice, but declaring a class MyText<T, T>
is attempting to declare T
twice.
A variable-equivalent analogy would be declaring a variable and using it twice:
int x;
...
x + x
vs. attempting to declare two variables with the same name.
int t;
int t;
You just need to make sure you know when you're declaring a type parameter and when you're using an existing type parameter.