I'm stuck on a simple thing. I have an array of booleans named "tags." It's important to me to be able to access each element of the array by boolean:
public boolean energetic, calming, happy, sad;
public boolean[] trackTags = {energetic, calming, happy, sad};
I pass in and assign boolean values to the trackTags array (let's say [true, true, true, false]. So, when I call trackTags[0], I get "true." However, when I print "energetic," - which should be the same as trackTags[0], the value is always false. I know booleans initialize false, but when I switch some values in the trackTags Array for "true," shouldn't the named elements change as well?
Second question: what's a good way for me to interact with boolean variable names? Specifically, if I pass in a String[] [happy, sad], and then want to switch only the boolean[] values corresponding to names in my String array, is this feasible? I have no trouble looping through the elements of both arrays, but I obviously can't compare a string to a boolean value.
All in all, is there a better way to interact with boolean names? I'm really confused about this.
It sounds more like you want something like a Map
. This will allow you to effectively name the values by mapping the name as a key
to a value
.
Example
Map<String, Boolean> trackTags = new HashMap<String, Boolean>();
trackTags.put("energetic", false);
NOTE
Just for good code readability, I'd also put the names in some final fields..
public static final String ENERGETIC = "energetic";
and access it like this..
trackTags.get(ENERGETIC);
That way if you need to change the name, you change it in one place and not all over the show.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With