Search code examples
javaequalsequals-operator

Not sure how to complete this equals method


Could someone help me with this question please? I've tried looking up other examples of this to find what I need to do and keep running into something called and EqualsBuilder, is that what I need to use? Do I need to have it call on equals again if it satisfies neither of the IFs?

The following code contains a class definition and an incomplete method definition. The equals method is used to compare Buildings. It is intended to return true if Buildings have the same names and number of floors (but are not necessarily the same Building) and false otherwise.

public class Building {      
    private String name;      
    private int noOfFloors;

    public boolean equals (Object rhs) {          
        if (this == rhs) { 
            return true; 
        }          
        if (!(rhs instanceof Building)) { 
            return false; 
        }          
        Building b = (Building) rhs;     

        // missing return statement      
    }  
}

Solution

  • public boolean equals (Object rhs) {          
        if (this == rhs) { 
            return true; 
        }          
        if (!(rhs instanceof Building)) { 
            return false; 
        }          
        Building b = (Building) rhs;     
    
        // This is what you're supposed to add. It will return true only if both
        // object's attributes (name and number of floors) are the same
        return this.name.equals(b.name) && this.noOfFloors == b.noOfFloors;
    }