3D-kreativ 3D-kreativ - 1 year ago 58
Java Question

How to check if objects in an array list has the same value?

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

that holds an int number representing

  1. for red

  2. for blue

  3. for white

  4. for yellow and finally

  5. for green.

So there a five objects of each color.

Each object also has a boolean value that I call
, and it's set to false at the beginning. But during the game, some of the Circle objects
are set to true.

All 25 objects are stored in an
that I call

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
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.

Some help would be nice!

Answer Source

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.

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.

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.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download