Reputation: 1225
Suppose I want to define an enum pointing to an array of objects. Can this be done? In the below code, the commented out part defines an enum pointing to single objects and works fine, but the uncommented code which tries to initialize arrays of objects causes a bunch of errors.
public enum SightSensor{
/*NORTH (new MapLocation(0,1)),
SOUTH (new MapLocation(0,-1));
private final MapLocation loc;
SightSensor(MapLocation loc){
this.loc = loc;
}
public MapLocation getLoc(){
return loc;
}*/
NORTH ({new MapLocation(0,1), new MapLocation(0,2)}),
SOUTH ({new MapLocation(0,-1), new MapLocation(0,-2)});
private final MapLocation[] locs;
SightSensor(MapLocation[] locs){
this.locs = locs;
}
public MapLocation[] getLocs(){
return locs;
}
}
On a related note, suppose I wanted to define a fixed mapping between two enums: what's the best way to do so? Map? Hash? To be precise, suppose analogously to the above code I wanted to define an object A that that if NORTH is a different enum value A[NORTH] will return the desired list of MapLocations.
Upvotes: 1
Views: 2026
Reputation: 51030
Always keep in mind that { }
can be used to define an array only when it's used in the statement that also declares the array.
e.g.
MapLocation[] locs = {new MapLocation(0,1), new MapLocation(0,2)};
Upvotes: 0
Reputation: 718718
I think it should be this:
NORTH (new MapLocation[]{new MapLocation(0,1), new MapLocation(0,2)}), ...
The bare {...}
construct cannot be used in that context.
Upvotes: 2