【发布时间】:2016-08-15 21:57:43
【问题描述】:
我编写了一个小脚本来获取图像的像素并将其放入 ArrayList 中,然后创建一个包含这些值的类。
这是我的代码的一部分:
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 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 不相等,即使它们具有相同的属性。怎么能这样?
【问题讨论】:
-
因为你没有实现
equals,所以它比较引用,不一样。 -
您需要实现
Object.equals方法(如果您计划使用实例,例如在Maps 内,您应该对hashCode执行相同的操作),您是否比较了所有属性。跨度> -
相关:stackoverflow.com/q/27581/3182664(以及其他数千个问题)
-
您在构造函数中的哪个位置设置了红色、绿色或蓝色的值?为什么要遍历
RGBColor数组的 3 个元素,并且在每次迭代时每三个值重新计算并覆盖一些HEXA值?是否有充分的理由违反使字段看起来像常量的基本命名准则?请先纠正代码中与实例相等无关的小错误...然后让您的 IDE 生成equals和hashCode以解决您所询问的实际问题。 -
@OlegSklyar 你是对的。我什至不知道我为什么这样做!谢谢。
标签: java object compare equality