2

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

3
  • 2
    Well now, there's an example of a terrible compiler error message! Commented Nov 4, 2009 at 4:14
  • 2
    Basic syntax FAIL. Back to driving school, Sonny! Commented Nov 4, 2009 at 6:54
  • 2
    Better do: List<List<Integer>> numSetSet = new ArrayList<List<Integer>>(); And if it's a set, why are you using lists? Commented Nov 4, 2009 at 7:36

5 Answers 5

22

You forgot the word new.

Sign up to request clarification or add additional context in comments.

Comments

7

That should be:

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

Or even better:

List<List<Integer>> numListList = new ArrayList<List<Integer>>();

4 Comments

Actually, you can't have nested Abstract types, apparently: List<ArrayList<Integer>> numSetSet = new ArrayList<ArrayList<Integer>>();
@Rosarch: List<List<Integer>> numListList = new ArrayList<List<Integer>>(); compiles just fine on my machine.
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: 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.
1

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

Comments

1

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/

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.