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
Perhaps you need:
class Foo<S>{
private S Boo ;
.
.
}
public class Test{
public static void main(String[] args){
Foo<ArrayList<String>> foo = new Foo<ArrayList<String>>();
}
}
This is invalid syntax
S<T>
because for anyone x<T>
, x
must be a known class or interface type.
What you want is the container type and the element type. It is possible
class Foo<C extends Collection<E>, E>{
private C boo;
...
Foo<ArrayList<String>, String> foo = new Foo<>();
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;
}