Java 类型字符串的方法(x)未定义

Java 类型字符串的方法(x)未定义,java,object,Java,Object,所以我有两个字符串:类型和颜色。由于某些原因,我不能使用“getType”或“getColor”。错误出现在第二个方法的底部(publicbooleanequals(stringaclothing))。我怎样才能解决这个问题 public class Clothing { // Attributes private String type; private String color; // Constructors public Clothing()

所以我有两个字符串:类型和颜色。由于某些原因,我不能使用“getType”或“getColor”。错误出现在第二个方法的底部(publicbooleanequals(stringaclothing))。我怎样才能解决这个问题

public class Clothing {

    // Attributes
    private String type;
    private String color;

    // Constructors
    public Clothing() {
        this.type = "no type yet";
        this.color = "no color yet";
    }

    public Clothing(String aType, String aColor) {
        this.setType(aType);
        this.setColor(aColor);
    }

    // Accessors (getters)
    public String getType() {
        return this.type;
    }

    public String getColor() {
        return this.color;
    }

    // Mutators (setters)
    public void setType(String aType) {

        this.type = aType; // TODO check invalid values
    }

    public void setColor(String aColor) {
        this.color = aColor; // TODO check invalid values
    }

    // Methods
    public String toString() {
        return this.type + " " + this.color;
    }

    public boolean equals(String aClothing) {
        return aClothing != null && this.type.equals(aClothing.getType()) && this.color.equals(aClothing.getColor());
    }
}

a服装
的类型为
String
而非
服装

String
没有
getType/getColor
方法。

问题是您为比较方法传入了一个字符串:

public boolean equals(String aClothing) <--- here your input type is a string
{
    return aClothing != null &&
            this.type.equals(aClothing.getType())&&
            this.color.equals(aClothing.getColor());
}

您应该实现
equals
作为的重写,这意味着您的方法需要将
对象
作为参数:

@Override
public boolean equals(object aClothingObj) {
    if (aClothingObj == this) return true; // reference check for this
    if (!(aClosingObj instanceof Clothing)) return false;
    Clothing aClothing = (Clothing)aClothingObj;
    return this.type.equals(aClothing.getType()) &&
           this.color.equals(aClothing.getColor());
}
当您重写
等于
时,还必须重写
哈希代码

@Override
public int hashCode() {
    return 31*type.hashCode()+color.hashCode();
}

这两种方法的可能重复都不会真正满足OP的要求,正确使用
@Override
将标记错误。正确的签名是
布尔等于(对象)
。您是正确的。我完全忘记了正确的方法签名。
@Override
public int hashCode() {
    return 31*type.hashCode()+color.hashCode();
}