3D-kreativ 3D-kreativ - 3 months ago 7
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

color
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
status
, and it's set to false at the beginning. But during the game, some of the Circle objects
status
are set to true.

All 25 objects are stored in an
ArrayList
that I call
listOfCircles
.

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.

Some help would be nice!

Answer

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.