0

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"?

1
  • 1
    Note that a primitive boolean cannot be 'empty'. The value false is just as valid as true, and false does not mean the value is unused. If you really want to distinguish "empty" from a valid boolean you must use Boolean objects, so the reference can be null to indicate "empty". Commented Oct 15, 2013 at 17:14

3 Answers 3

4

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.

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

1 Comment

+1, but some alignment and braces would make it easy to read, atleast to me
2

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.

Comments

2

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;
}

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.