views:

227

answers:

4

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

+20  A: 

You forgot the word new.

Jonathan Feinberg
WOW it is getting too late. thanks.
Rosarch
+7  A: 

That should be:

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

Or even better:

List<List<Integer>> numListList = new ArrayList<List<Integer>>();
Asaph
Actually, you can't have nested Abstract types, apparently:`List<ArrayList<Integer>> numSetSet = new ArrayList<ArrayList<Integer>>();`
Rosarch
@Rosarch: `List<List<Integer>> numListList = new ArrayList<List<Integer>>();` compiles just fine on my machine.
Asaph
The second solution may not be better. In the second solution any kind of list can be put in the main list which may not what you want.In fact you could put both ArrayList and LinkedList into the main list. It may not be a bad thing, but may not be what you want.
fastcodejava
@fastcodejava: That's exactly the point! Always code to an interface, not an implementation. That way you can swap out different implementations of the `List` interface easily without changing lots of code.
Asaph
+1  A: 

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

instanceofTom
+1  A: 

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/

Zanyking