简体   繁体   中英

Java HashMap Iterate Each Variable and Return Value

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

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.

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 .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM