由于color 似乎是一个Color,所以是一个类,因此是一个引用类型,这意味着您需要使用它们equals()来比较颜色。
if ( this.color.equals(other.color)) {如注释中所述,==用于比较引用类型实际上是比较Java中的内存地址。仅true当它们都
引用内存中的同一对象时,它才会返回。
akf指出,您需要
Object为参数使用基类,否则,您不会覆盖
Object.equals(),而是实际上将其重载,即提供了一种不同的调用同名方法的方法。如果您偶然偶然传递了一个完全不同的类的对象,则可能会发生意外的行为(尽管如果它们属于
不同的类,则仍然会false正确返回)。
@Overridepublic boolean equals(Object obj) { if (!(obj instanceof Ghost)) return false; // Cast Object to Ghost so the comparison below will work Ghost other = (Ghost) obj; return this.x == other.x && this.y == other.y && this.direction == other.direction && this.color.equals(other.color);}


