[英]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. boolean isEmpty()方法将告诉我所有值是否为空。
Now, I want to move all my data into HashMaps: 现在,我想将所有数据移动到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"? 我的问题与“ boolean isEmpty()”方法有关,如何使此函数遍历每个HashMap(无论大小),并检查以确保每个值都是“ false”或“ 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; 在每个地图上调用
values()
方法 ; you can iterate through the returned Collection
of values. 您可以遍历返回的值的
Collection
。 Then you can check each value to see if they are 0
or false
as the case may be. 然后,您可以检查每个值以查看它们是否为
0
或false
视情况而定)。
Keep a boolean
, initialized to true
, if everything is "empty" so far. 如果到目前为止所有内容都是“空”,则保留一个
boolean
,将其初始化为true
。 Set it to false
if a value isn't 0
or false
. 其设置为
false
,如果值不是0
或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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.