I've been trying to do this for a little while and it's driving me crazy. I have an EnumMap where I have some enumeration as a key and an arraylist of a self-defined class as the value. So it looks something like this:
private EnumMap<myEnum,List<myObj>> map =
new EnumMap<myEnum,List<myObj>>(myEnum.class);
This keeps giving me an error. Not sure exactly what's happening.
EDIT: Yes, myEnum is an enum class. My mistake, I should have mentioned what error is and where it happens. The error occurs when I do the following:
h开发者_运维百科and.put(myEnum.someEnum, new ArrayList());
The error I get is: - Syntax error on tokens, TypeArgument1 expected instead - Syntax error on token "(", < expected - Syntax error on token "new", delete this token
For:
enum Test {
TEST0,
TEST1;
}
You would use the EnumMap
like this:
EnumMap<Test, List<Object>> map = new EnumMap<Test, List<Object>>(Test.class);
map.put(Test.TEST0, new ArrayList<Object>());
Hopefully that clears up the usage.
Also, I assume myEnum refers to the class name and not an instance of class MyEnum and same for myObj. We usually start class names with uppercase letters, so this is a little bit confusing.
hand.put(myEnum.someEnum, new ArrayList());
You need to parameterize the ArrayList with ();
hand.put(myEnum.someEnum, new ArrayList());
should be like this:
map.put(myEnum.someEnum, new ArrayList<myObj>());
melv's code seems to work:
import java.util.*;
enum Color {
r,g,b;
}
public class Main{
public static void main(String[] args) {
EnumMap<Color, List<Object>> map = new EnumMap<Color, List<Object>>(Color.class);
map.put(Color.r, new ArrayList<Object>());
map.get(Color.r).add(new Integer(42));
System.out.println(map.get(Color.r).get(0));
}
}
精彩评论