Home > Net >  Switching a compare to function to a boolean in Java
Switching a compare to function to a boolean in Java

Time:04-19

I am trying to change the compareTo after @override to a boolean function. This function will take a generic Object o and return whether or not it equals that Ingredient object. The only attribute in ingredient is name. So cast Object o to a Ingredient and then return whether the string names equal.

public class Ingredient implements Comparable<Ingredient> {

    private String name;
    
    public Ingredient(String name) {
        this.name = name;
    }
    
    public String getName() {
        return this.name;
    }

    /**
     * Compares two ingredients.
     * 
     * note: if we add other ingredient attributes,
     * we will need to change this method.
     */
    @Override
    public int compareTo(Ingredient other) {
        return this.name.compareTo(other.name);
    }
    

}

So, I change the last function to: Does this work? Or, am I on the right track...

public boolean equals(Object o){
            if(this == o) return true;
            Ingredient ingredient = (Ingredient)o;
            if(ingredient.name.equals(this.name)) {
                return true;
            } else return false;
    }

CodePudding user response:

You don't even have to use an interface.

According to the Java Docs, a Comparable is being used specify and order, e.g. sorting an Array.

To check for equality, you have to override the method equals (and not even implement some interface), which returns a boolean:

  • true for equality
  • false for inequality

Also, changing the return type of inherited methods is not allowed in java.

CodePudding user response:

You are overwriting the int compareTo() Method of the Object class. There is no bool compareTo() to overwrite. It just doesn't exists.

When overwriting int compareTo(), you should return 0 if the objects are equal, a negative number if other is greater than this and a positive number if other is smaller than this

  •  Tags:  
  • java
  • Related