-1

So I have two Strings: type and color. For some reason I can't use "getType" or "getColor". The error comes at the bottom in the second method (public boolean equals(String aClothing)). How can I fix this?

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());
    }
}
Malt
  • 28,965
  • 9
  • 65
  • 105
  • Possible duplicate of [How to implement hashCode and equals method](https://stackoverflow.com/questions/2132334/how-to-implement-hashcode-and-equals-method) – Iłya Bursov Oct 26 '17 at 19:10

3 Answers3

1

You should implement equals as an override of java.lang.Object's equals method, which means that your method needs to take Object as a parameter:

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

When you override equals, you must also override hashCode:

@Override
public int hashCode() {
    return 31*type.hashCode()+color.hashCode();
}
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
-1

aClothing is of type String not Clothing. String has no getType/getColor method.

Malt
  • 28,965
  • 9
  • 65
  • 105
-1

The problem is that you pass in a String for your comparison method:

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

Instead, your method for equals should take in a generic object and override the equals method that all objects have:

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