declare enum for using in array?
Sorry for probably easy question.
I need array of flags
boolean[20] isTownVisited
But it is not convient to use int in it, i wan开发者_JAVA技巧t to use strings:
isTownVisited[Town.Milan] = true;
or
return isTownVisited[Town.Rome]
I've tried to declare enum
enum Town {Milan, Rome, Florence, Napoli}
But I still can't use it to index my boolean array. How to fix this problem, may I write something like:
enum Town {Milan = 0, Rome = 1, Florence = 2, Napoli = 3}
You can use an EnumSet.
Set<Town> towns = EnumSet.of(Town.Milan);
towns.add(Town.Rome);
return towns.contains(Town.Napoli);
Under the bonnet the EnumMap and EnumSet uses int ordinal();
The EnumSet uses a bitmap.
Gee... I would have just use this:
boolean[Town.values().length] isTownVisited;
isTownVisited[Town.Milan.ordinal] = true;
u can always make a public static class with all the variables declared
so
public class Town{
public static bool Rome = false;
// and the rest
}
Then u can simply do Town.rome to acess the variables...
Note dont make static variables if you want to use these variables inside multiple objects.
In that case make normal variables and then create a new object and use the variables of that object
It sounds like you need a map instead of an array. You can create a Map<Town, Boolean>
, where Town
is an enum, and the boolean is whether that town has been visited or not.
精彩评论