比较 Java 中的相同对象

Compare same objects in Java

我写了一个小脚本来获取图像的像素并将其放入 ArrayList 中,然后我创建了一个包含这些值的 class。

这是我的部分代码:

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 !");

以及 class 颜色:

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;
    }

    //...

}

但我不明白为什么变量 red 与变量 red2 不相等,即使它们具有相同的属性。怎么做到的?

您需要在您的 Color class.

中覆盖并实施 equals() 和随后的 hashcode()

类似于:

@Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + BLUE;
        result = prime * result + GREEN;
        result = prime * result + ((HEXA == null) ? 0 : HEXA.hashCode());
        result = prime * result + RED;
        return result;
    }

@Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Color other = (Color) obj;
        if (BLUE != other.BLUE)
            return false;
        if (GREEN != other.GREEN)
            return false;
        if (HEXA == null) {
            if (other.HEXA != null)
                return false;
        } else if (!HEXA.equals(other.HEXA))
            return false;
        if (RED != other.RED)
            return false;
        return true;
    }

java.lang.Object 上的默认 equals() 方法比较内存地址,这意味着所有对象彼此不同(只有对同一对象的两个引用才会 return 为真)。

因此您需要覆盖 Color class 的 equals() 和 hashcode() 方法才能使代码正常工作。