Search code examples
javaobjectcompareequality

Compare same objects in Java


I write a little script to get pixel of an image and put it in an ArrayList, and i create a class who contains these values.

Here a parts of my code:

int arrC[] = {255, 0, 0};
Color   red = new Color(arrC),
        red2 = new Color(arrC);
if(!red.equals(red2)) System.out.print("It's not the same color !");

And the class Color:

class Color {

    private int RED;
    private int GREEN;
    private int BLUE;
    private String HEXA;

    public Color(int RGBColors[]) throws ColorException {
        if(RGBColors.length == 3) {
            for(int rgbcolor : RGBColors) {
                HEXA = String.format("#%02x%02x%02x", RGBColors[0], RGBColors[1], RGBColors[2]);
            }
        }else {
            throw new ColorException("Erreur : Number of the value incorrect. 3 excepted not: " + RGBColors.length);
        }
    }

    public Color(int hexacolor) {
        System.out.println(hexacolor);
    }

    /* Getter & Setters */

    public int getRED() {
        return this.RED;
    }

    //...

}

But i don't understand why variable red are not equals with the variable red2 even if they have the same propreties. How can do that ?


Solution

  • The default equals() method on java.lang.Object compares memory addresses, which means that all objects are different from each other (only two references to the same object will return true).

    So you need to override equals() and hashcode() method of the Color class for the code to work properly.