版本 2.X
JavaFX 显然是部分开源的(堆栈溢出参考)。从该链接中,我找到了2.X版本的类中equals()
方法的源代码:Color
/**
* Indicates whether some other object is "equal to" this one.
* @param obj the reference object with which to compare.
* @return {@code true} if this object is equal to the {@code obj} argument; {@code false} otherwise.
*/
@Override public boolean equals(Object obj) {
if (obj == this) return true;
if (obj instanceof Color) {
Color other = (Color) obj;
return red == other.red
&& green == other.green
&& blue == other.blue
&& opacity == other.opacity;
} else return false;
}
显然,red
、green
、blue
和opacity
需要相同。
版本 1.X
对于1.X版本,我只是查看了编译的类文件,并有足够的信心说实现与 2.X 相同(下面的片段):
@com.sun.javafx.runtime.annotation.Public
public boolean equals(java.lang.Object arg0);
4 invokestatic javafx.lang.Builtins.isSameObject(java.lang.Object, java.lang.Object) : boolean [87]
15 instanceof javafx.scene.paint.Color [80]
18 ifeq 121
22 checkcast javafx.scene.paint.Color [80]
28 invokevirtual javafx.scene.paint.Color.get$red() : float [45]
38 invokevirtual javafx.scene.paint.Color.get$red() : float [45]
50 invokevirtual javafx.scene.paint.Color.get$green() : float [47]
60 invokevirtual javafx.scene.paint.Color.get$green() : float [47]
72 invokevirtual javafx.scene.paint.Color.get$blue() : float [48]
82 invokevirtual javafx.scene.paint.Color.get$blue() : float [48]
94 invokevirtual javafx.scene.paint.Color.get$opacity() : float [49]
104 invokevirtual javafx.scene.paint.Color.get$opacity() : float [49]
从 1.X 到 2.X的equals()
实现没有改变。
你真正的问题
如果Color1
并且Color2
确实是 type Color
,您正在将它们与 type 的对象进行比较String
:
if(Color1.equals("yellow")) && (Color2.equals("yellow"))
比较将在此处失败:
if (obj instanceof Color)
因此,该equals()
方法将始终返回 false。您应该equals()
与另一个类型的对象一起使用Color
。