方法(x)未定义String类型

时间:2017-10-26 19:08:03

标签: java object

所以我有两个字符串:类型和颜色。出于某种原因,我不能使用“getType”或“getColor”。错误出现在第二种方法的底部(public boolean equals(String aClothing))。我该如何解决这个问题?

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

3 个答案:

答案 0 :(得分:1)

您应该将equals实现为java.lang.Object's equals method的覆盖,这意味着您的方法需要将Object作为参数:

@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());
}

覆盖equals时,您还必须覆盖hashCode

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

答案 1 :(得分:-1)

aClothing的类型为String而不是ClothingString没有getType/getColor方法。

答案 2 :(得分:-1)

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

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的方法应该包含一个泛型对象并覆盖所有对象具有的equals方法:

@Override
public boolean equals(Object aClothing)
{
    return aClothing instanceof Clothing && aClothing != null && 
            this.type.equals(aClothing.getType())&&
            this.color.equals(aClothing.getColor());
}