简体   繁体   English

如何重写equals和tostring方法

[英]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. 我认为这些方法存储在java.lang.Object中,但我无法弄清楚如何在代码中覆盖它们。 Here's a little program I designed to test my understanding (which wasn't right). 这是我设计的一个小程序来测试我的理解(这是不对的)。

AddressTester: 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()的好参考 :正如他们所提到的那样

equals should usually compare state, not identity. equals通常应该比较状态,而不是身份。 This is particularly true for "data-centric" classes which map to database records. 对于映射到数据库记录的“以数据为中心”的类尤其如此。

In this example I override hashCode, toString and equals. 在这个例子中,我重写了hashCode,toString和equals。 My criteria is that equals should use someAttribute of SomeClass to define de equals() between said class instances. 我的标准是equals应该使用someClass的someAttribute来定义所述类实例之间的de equals()。 HashCode should be redefined alongside with equals in the same way. HashCode应该以相同的方式与equals一起重新定义。

@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. 如果您使用的是Eclipse IDE,它会为您提供默认情况下生成,equals,hashCode和toString函数的功能。

also you have to use some kind of class variables in your equals method to compare upon. 你还必须在equals方法中使用某种类变量来进行比较。

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 . 当应用于Object的实例时, ==运算符检查是否在对该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. 如果使用相同的地址,城市,州和邮政编码创建了两个Address实例,则==运算符在用于比较这两个不同的实例时将返回false 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. 您需要使用函数覆盖Address上的equals()以显式检查4个字段中的每个字段是否匹配,并在这种情况下返回true

Constructing a sound equals() overriding implementation is tricky to get right and you should definitely check out the links other posters have provided. 构建一个声音equals()重写实现是很难的,你应该检查其他海报提供的链接。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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