Java: Nested generics?

1.8k Views Asked by At

Can Java nest generics? The following is giving me an error in Eclipse:

ArrayList<ArrayList<Integer>> numSetSet = ArrayList<ArrayList<Integer>>();

The error is:

Syntax error on token "(", Expression expected after this token

5

There are 5 best solutions below

0
Jonathan Feinberg On BEST ANSWER

You forgot the word new.

4
Asaph On

That should be:

ArrayList<ArrayList<Integer>> numSetSet = new ArrayList<ArrayList<Integer>>();

Or even better:

List<List<Integer>> numListList = new ArrayList<List<Integer>>();
0
Tom Neyland On

For those who come into this question via google, Yes Generics can be nested. And the other answers are good examples of doing so.

0
Zanyking On

And here are some slightly tricky technic about Java template programming, I doubt how many people have used this in Java before.
This is a way to avoid casting.

public static <T> T doSomething(String... args) 

This is a way to limit your argument type using wildcard.

public void draw(List<? extends Shape> shape) {  
    // rest of the code is the same  
}  

you can get more samples in SUN's web site:
http://java.sun.com/developer/technicalArticles/J2SE/generics/

0
Patchikori Rajeswari On

You forgot 'new' keyword as in below code:

ArrayList<ArrayList<Integer>> numSetSet = new ArrayList<ArrayList<Integer>>();

You can also use Maps along with Lists for nested Generics as shown in Java 5 (J2SE 5.0/JDK 1.5) New Features with Examples