声明枚举以在数组中使用?
抱歉,这个问题可能很简单。
我需要标志数组
boolean[20] isTownVisited
,但在其中使用 int 并不方便,我想使用 strings:
isTownVisited[Town.Milan] = true;
或者
return isTownVisited[Town.Rome]
我尝试声明 enum
enum Town {Milan, Rome, Florence, Napoli}
但我仍然无法使用它来索引我的布尔数组。如何解决这个问题,我可以写一些类似的内容:
enum Town {Milan = 0, Rome = 1, Florence = 2, Napoli = 3}
Sorry for probably easy question.
I need array of flags
boolean[20] isTownVisited
But it is not convient to use int in it, i want 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}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
哎呀......我只想用这个:
Gee... I would have just use this:
你总是可以创建一个公共静态类,并声明所有变量
,所以
然后你可以简单地执行 Town.rome 来访问变量...
注意,如果你想在多个对象中使用这些变量,请不要创建静态变量。
在这种情况下,创建普通变量,然后创建一个新对象并使用该对象的变量
u can always make a public static class with all the variables declared
so
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
听起来您需要一个地图而不是一个数组。您可以创建一个
Map
,其中Town
是一个枚举,布尔值是该城镇是否已被访问过。It sounds like you need a map instead of an array. You can create a
Map<Town, Boolean>
, whereTown
is an enum, and the boolean is whether that town has been visited or not.您可以使用 EnumSet。
在本质上,EnumMap 和 EnumSet 使用
int ordinal();
EnumSet 使用位图。You can use an EnumSet.
Under the bonnet the EnumMap and EnumSet uses
int ordinal();
The EnumSet uses a bitmap.