Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to create object using two Generics in Java?

Tags:

java

generics

I want to define instance variables using two Generics like below.

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 doesn't work... Is it kinda wrong grammar? I really need to this kind of grammar.

like image 602
user3595632 Avatar asked Dec 06 '25 04:12

user3595632


2 Answers

This is invalid syntax

S<T>

because for any x<T>, x must be a known class or interface type.

What you want is a container type and an element type. This is possible

class Foo<C extends Collection<E>, E>{
    private C boo;

...

Foo<ArrayList<String>, String> foo = new Foo<>();
like image 156
ZhongYu Avatar answered Dec 07 '25 20:12

ZhongYu


Maybe 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>>();          

    }
}
like image 30
chengpohi Avatar answered Dec 07 '25 21:12

chengpohi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!