Java: Nested generics?
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
You forgot the word new
.
That should be:
ArrayList<ArrayList<Integer>> numSetSet = new ArrayList<ArrayList<Integer>>();
Or even better:
List<List<Integer>> numListList = new ArrayList<List<Integer>>();
For those who come into this question via google, Yes Generics can be nested. And the other answers are good examples of doing so.
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/
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
精彩评论