Naming Boolean Elements in a Java Boolean Array

I am stuck in a simple thing. I have an array of gates called tags. It is important for me to have access to each element of the array using boolean:

public boolean energetic, calming, happy, sad;
public boolean[] trackTags = {energetic, calming, happy, sad};

I pass and assign booleans to the trackTags array (say [true, true, true, false]. Therefore, when I call trackTags [0], I get “true”. However, when I type “energetic”, which should be the same like trackTags [0], the value is always false. I know that booleans initializes false, but when I switch some values ​​to the trackTags array for true, should the named elements also not change?

Second question: what is a good way for me to interact with boolean variable names? In particular, if I pass the string [] [happy, sad], and then I want to switch only the boolean [] values ​​corresponding to the names in my String array, is this possible? I have no problem with the loop of elements in both arrays, but I obviously cannot compare the string to a boolean.

In general, is there a better way to interact with logical names? I am really confused by this.

+4
source share
3 answers

It is like you want something like Map. This will allow you to effectively name values ​​by matching the name as keywith value.

Example

Map<String, Boolean> trackTags = new HashMap<String, Boolean>();

trackTags.put("energetic", false);

Note

.

public static final String ENERGETIC = "energetic";

.

trackTags.get(ENERGETIC);

, , .

+11

trackTags. , "", . , booleans false, trackTags "true", ?

. boolean , , .

?

, ( ). Map<String, Boolean>.

+5

An alternative to using the Card would be to define a separate set of transfers.

enum tagNames = {energetic, calming, happy, sad};
boolean tags[] = new boolean[4];

Then you can change the current current boolean array as usual:

for(int i = 0; i < tags.length; i++){
    if (tags[i] == 1)
        trackTags[i] = true;
}

But you can also search for specific values ​​using your enumerations:

tags[tagNames.energetic.ordinal()] //returns boolean value at [0]

* I would like to add that this method is probably not recommended due to customization issues. For example, if you want your enumerations to refer to elements of another array that are offset from 0.

+2
source