如何检查数组列表中的对象是否具有相同的值?
我正在为 Android 平台做一个简单的游戏.我有 25 个对象由我称为 Circle 的类制成.每个 Circle 对象都有一个字段 color
,它保存一个代表
I'm doing a simple game for the Android platform. I have 25 objects made from the class that I call Circle. Each Circle object has the field color
that holds an int number representing
- 红色
- 蓝色
- 白色
- 黄色,最后
- 绿色.
所以每种颜色有五个对象.
So there a five objects of each color.
每个对象还有一个布尔值,我称之为status
,并且在开始时设置为false.但是在游戏过程中,某些 Circle 对象 status
被设置为 true.
Each object also has a boolean value that I call status
, and it's set to false at the beginning. But during the game, some of the Circle objects status
are set to true.
所有 25 个对象都存储在我称为 listOfCircles
的 ArrayList
中.
All 25 objects are stored in an ArrayList
that I call listOfCircles
.
我的问题是,如何检查所有设置为 true 的 Circle 对象是否具有相同类型的颜色代码?假设三个 Circle 对象设置为 true,每个对象 color
都是 3,但也可能是这三个 Circle 对象中的一个值为 1,另外两个为 4,然后这不是有效匹配.
My question is, how can I check if all Circle objects that are set to true has the same type of color code? Let's say that three Circle objects are set to true and each objects color
are 3, but the case could also be that on of this three Circle object could have the value of 1 and the other two 4, then it's not a valid match.
一些帮助会很好!
它是这样工作的.它遍历圆圈列表并查找第一个具有 status = true
的圆圈.当它找到它时,它会将那个圆圈的颜色保存在 int color
中.在此后的每一步,如果它找到一个活动圆圈(status = true
,它会检查该圆圈的颜色是否与原始圆圈匹配.
It works like this. It goes through the list of circles and looks for the first one that has status = true
. When it finds it, it saves the color of that circle in int color
. At every step thereafter, if it finds an active circle(with status = true
, it checks to see if the color of that circle matches the original one.
如果不是,则表示并非所有活动的圆圈都具有相同的颜色.由于 flag
最初设置为 true
,单个 false
就足以确定并非所有活动圆圈的颜色都相同.
If it doesn't then it means not all active circles have the same color. Because the flag
was originally set to true
, a single false
is enough to know for sure that not all active circles are of the same color.
如果没有找到false
,这意味着如果所有活动圆圈与第一个活动圆圈的颜色相同,则flag
保持true
.
If no false
is found, which means if all active circles have the same color as the first active circle, then the flag
remains true
.
List<Circle> listOfCircles = new ArrayList<Circle>();
boolean flag = true;
int color;
for (Circle currentCircle: listOfCircles) {
if (currentCircle.status == true) {
if (color == null) {
color = currentCircle.color;
} else {
if (color != currentCircle.color) {
flag = false;
};
};
};
};
// flag now holds true or false according to your needs.