2

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}

4 Answers 4

6

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.

Sign up to request clarification or add additional context in comments.

Comments

1

Gee... I would have just use this:

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

isTownVisited[Town.Milan.ordinal] = true;

1 Comment

thanks that's probably what I was looking for :) but now EnumSet looks pretty good... I've tried use it and I'm happy with it because collections more easy to use than arrays...
0

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

6 Comments

i would loose ability of iterating all towns
assign unique indexes to the towns in the static class and create an array of bools as u did originally. That way you can get both iteration as well as the ablility to use names..
e.g rome = 0; london =1 ; etc all constants
so isVisited[0] becomes isvisited[Towns.rome].. Hopefully this solves your problem
P.S I believe you can cast enums to int x = (int) Town.Rome;
|
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.