Reputation: 101
I have a class with various Booleans and Integers.
class Animal {
boolean mHappy = false;
boolean mHungry = false;
boolean mSleeping = false;
int mCost = 0;
int mWeight = 0;
boolean isEmpty() {
return !mHappy && !mHungry && !mSleeping && mCost == 0 && mWeight == 0;
}
}
The method boolean isEmpty() will tell me if all the values are empty.
Now, I want to move all my data into HashMaps:
class Animal {
HashMap<String, Boolean> mBools = new HashMap<String, Boolean>(){{
put("mHappy", false);
put("mHungry", false);
put("mSleeping", false);
}
};
HashMap<String, Integer> mInts = new HashMap<String, Integer>(){{
put("mCost", 0);
put("mWeight", 0);
}
};
boolean isEmpty() {
// MY QUESTION: How can I make this function iterate through each HashMap,
// regardless of size, and check to make sure it's "false" or "0" like this
// line did when I only was using static booleans and integers?
return !mHappy && !mHungry && !mSleeping && mCost == 0 && mWeight == 0;
}
}
My Question is about the "boolean isEmpty()" method, How can I make this function iterate through each HashMap, regardless of size, and check to make sure each value is "false" or "0"?
Upvotes: 0
Views: 1348
Reputation: 736
You just need to iterate over the values in your maps:
boolean isEmpty {
for (Integer i : mInts.values()) {
if (i > 0) {
return false;
}
}
for (Boolean b : mBools.values()) {
if (b) {
return false;
}
}
return true;
}
Upvotes: 2
Reputation: 50021
This will do it:
boolean isEmpty() {
for (int i : mInts.values()) if (i != 0) return false;
for (boolean b : mBools.values()) if (b) return false;
return true;
}
Read the map tutorial for more info about iterating through the contents of a map.
Upvotes: 4
Reputation: 178253
Call the values()
method on each map; you can iterate through the returned Collection
of values. Then you can check each value to see if they are 0
or false
as the case may be.
Keep a boolean
, initialized to true
, if everything is "empty" so far. Set it to false
if a value isn't 0
or false
.
Upvotes: 2