Is it possible to create an object using two Generics in Java?
I want to define instance variables using two generic types like belows.
class Foo<S,T>{
private S<T> Boo ;
.
.
}
public class Test{
public static void main(String[] args){
Foo<ArrayList, String> foo = new Foo<ArrayList, String>();
}
}
But it won't work ... Is this the wrong grammar? I really need this gram. Thanks to
+3
source to share
3 answers
It won't work because it ArrayList
has its own parameter and when you don't specify it it will be treated as an ArrayList.
Thus, your code will be invalidated private ArrayList<Object><String>
.
In such cases, you simply specify ArrayList<String>
and have your definition like this:
class Foo<S>{
private S Boo ;
.
.
}
public class Test{
public static void main(String[] args){
Foo<ArrayList, String> foo = new Foo<ArrayList<String>>();
}
}
If you want to place constraints on T
and S
, you can do it like this:
class Foo<S extends Collection<T>, T extends Comparable<T>> {
private S Boo;
}
But you cannot do
class Foo<S<T>, T extends Comparable<T>> {
private S Boo;
}
0
source to share