声明枚举以在数组中使用?

发布于 2024-11-25 03:31:28 字数 478 浏览 3 评论 0原文

抱歉,这个问题可能很简单。

我需要标志数组

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

无风消散 2024-12-02 03:31:29

哎呀......我只想用这个:

boolean[Town.values().length] isTownVisited;

isTownVisited[Town.Milan.ordinal] = true;

Gee... I would have just use this:

boolean[Town.values().length] isTownVisited;

isTownVisited[Town.Milan.ordinal] = true;
迷乱花海 2024-12-02 03:31:29

你总是可以创建一个公共静态类,并声明所有变量

,所以

public class Town{
   public static bool Rome = false;
   // and the rest
}

然后你可以简单地执行 Town.rome 来访问变量...

注意,如果你想在多个对象中使用这些变量,请不要创建静态变量。

在这种情况下,创建普通变量,然后创建一个新对象并使用该对象的变量

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

北笙凉宸 2024-12-02 03:31:29

听起来您需要一个地图而不是一个数组。您可以创建一个 Map,其中 Town 是一个枚举,布尔值是该城镇是否已被访问过。

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.

纸短情长 2024-12-02 03:31:28

您可以使用 EnumSet。

Set<Town> towns = EnumSet.of(Town.Milan);

towns.add(Town.Rome);

return towns.contains(Town.Napoli);

在本质上,EnumMap 和 EnumSet 使用 int ordinal(); EnumSet 使用位图。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文