简体   繁体   中英

How to override equals to and tostring methods

I'm trying to figure out how this works. I get the idea that the methods are stored in java.lang.Object but I can't figure out how to override them in the code. Here's a little program I designed to test my understanding (which wasn't right).

AddressTester:

import java.util.ArrayList;
import java.util.Scanner;

public class AddressTester
{

    public static void main(String[] args)
    {

        Address home = new Address("123 Loving Fat Girl ln", "Dollywood", "NY",
                "98765");

        Scanner in = new Scanner(System.in);

        System.out.println("-- Enter your home address --");
        System.out.println("123 Loving Fat Girl ln, Dollywood, NY, 98765");

        System.out.print("Enter the street address: ");
        String addr = in.nextLine();

        System.out.print("Enter the city: ");
        String city = in.next();

        System.out.print("Enter the state: ");
        String state = in.next();

        System.out.print("Enter the zipcode: ");
        String zipcode = in.next();

        Address enteredAddress = new Address(addr, city, state, zipcode);

        System.out.println(enteredAddress);

        if (home.equals(enteredAddress))
        {
            System.out.println("You are correct!");
        }
        else
        {
            System.out.println("You are incorrect!");
        }

        ArrayList<Address> addresses = new ArrayList<Address>();
        addresses.add(home);

        if (addresses.contains(enteredAddress))
        {
            System.out.println("The address wasn't found");
        }
        else
        {
            System.out.println("The address was found");
        }

    }

}

Address:

public class Address
{
    private String address;
    private String city;
    private String state;
    private String zipcode;


    public Address(String address, String city, String state, String zipcode)
    {
        this.address = address;
        this.city = city;
        this.state = state;
        this.zipcode = zipcode;

    }

    public boolean equals(Object otherObject)
    {
        if(otherObject == this)
        {
            return true;
        }
        if(otherObject != this)
        {
            return false;
        }
        return true;
    }

    public String getAddress()
    {
        return address;
    }

    public void setAddress(String addr)
    {
        this.address = addr;
    }

    public String getCity()
    {
        return city;
    }

    public void setCity(String city)
    {
        this.city = city;
    }

    public String getState()
    {
        return state;
    }

    public void setState(String state)
    {
        this.state = state;
    }

    public String getZipcode()
    {
        return zipcode;
    }

    public void setZipcode(String zipcode)
    {
        this.zipcode = zipcode;
    }

}

you're just checking for identity, which is not really what you want. check out this good reference about implementing equals(): as they mention

equals should usually compare state, not identity. This is particularly true for "data-centric" classes which map to database records.

In this example I override hashCode, toString and equals. My criteria is that equals should use someAttribute of SomeClass to define de equals() between said class instances. HashCode should be redefined alongside with equals in the same way.

@Override
public String toString() {
     return "SomeClass [attribute=" + someAttribute + "]";
}

@Override
public int hashCode() {
    final int prime = 31;
    int result = 1;
    result = prime * result + someAttribute;
    return result;
}
@Override
public boolean equals(Object obj) {
    if (obj == null)
        return false;       
    if (this == obj)
        return true;

    if (getClass() != obj.getClass())
        return false;
    SomeClass other = (SomeClass) obj;
    if (someAttribute != other.someAttribute)
        return false;
    return true;
}

this kind of question has been answered countless times.

if you are using Eclipse IDE, it provides you the functionality to generate, equals, hashCode and toString functions by default.

also you have to use some kind of class variables in your equals method to compare upon.

please do a google search to be blown away by innumerous results on the topic

The == operator, when applied to an instance of Object , checks whether the comparison is being made between two references to the same instance of that Object . If two instances of Address are created with the same address, city, state, and zipcode, the == operator will return false when used to compare those two different instances. You need to override equals() on Address with a function to explicitly check that each of the 4 fields match, and return true in that case.

Constructing a sound equals() overriding implementation is tricky to get right and you should definitely check out the links other posters have provided.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM