在Java中使用equals方法测试对象的相等性。

huangapple go评论42阅读模式
英文:

Testing equality of objects in Java with equals method

问题

我想问一个关于在Java中使用equals方法测试对象相等性的问题。

我是Java方面的初学者,目前正在学习《Java 9合1入门》这本书。

我编写了以下代码来检查两个Employee对象的相等性:

public class TestEquality2 {
    public static void main(String[] args) {
        Employee emp1 = new Employee("Martinez", "Anthony");
        Employee emp2 = new Employee("Martinez", "Anthony");
        if (emp1.equals(emp2))
            System.out.println("这些员工是相同的");
        else
            System.out.println("这些员工是不同的。");
    }
}

class Employee {
    private String firstName;
    private String lastName;

    public Employee(String firstName, String lastName) {
        this.lastName = lastName;
        this.firstName = firstName;
    }

    public String getLastName() {
        return this.lastName;
    }

    public String getFirstName() {
        return this.firstName;
    }

    public boolean equals(Object obj) {
        // 一个对象必须等于它自己
        if (this == obj)
            return true;

        // 没有对象等于null
        if (obj == null)
            return false;

        if (this.getClass() != obj.getClass())
            return false;

        // 转换为Employee,然后比较字段
        Employee emp = (Employee) obj;
        // 这是String的equals方法吗?
        return this.lastName.equals(emp.getLastName()) && this.firstName.equals(emp.getFirstName());
    }
}

引起关注的是equals(Object obj)方法的最后一行。

根据代码,我已经重写了默认的Object equals()方法并提供了自己的设计,但我在这里感到困惑:

return this.lastName.equals(emp.getLastName()) && this.firstName.equals(emp.getFirstName());

我知道lastName是一个字符串,但我在这里使用的equals()方法,是Stringequals()方法还是我刚刚定义的那个方法?如果是后者,我知道我会创建一个递归的情况,虽然我对于使用String equals()感到很有信心,但为了完整起见,我想澄清一下。

英文:

I want to ask a question about using the equals method to test object equality in Java.

I am a beginner in Java and currently progressing through the Dummies Java 9-in-1 book.

I have written the following code to check the equality of two Employee objects:

public class TestEquality2 {
public static void main (String [] args) {
Employee emp1 = new Employee ("Martinez", "Anthony");
Employee emp2 = new Employee ("Martinez", "Anthony");
if (emp1.equals(emp2))
System.out.println("These employees are the same");
else
System.out.println("These employees are different.");
}
}
class Employee {
private String firstName;
private String lastName;
public Employee (String firstName, String lastName) {
this.lastName = lastName;
this.firstName = firstName;
}
public String getLastName() {
return this.lastName;
}
public String getFirstName() {
return this.firstName;
}
public boolean equals (Object obj) {
// an object must equal itself
if (this == obj)
return true;
// no object equals null
if (this == null)
return false;
if (this.getClass() != obj.getClass())
return false;
// Cast to an employee, then compare the fields
Employee emp = (Employee) obj;
// is this the string's equals method?
return this.lastName.equals(emp.getLastName()) && this.firstName.equals(emp.getFirstName());
}
}

The line of concern is the last one of the equals(Object obj) method.

As per the code, I have overriden the default Object equals () method and supplied my own design, but I was confused here:

return this.lastName.equals(emp.getLastName()) && this.firstName.equals(emp.getFirstName());

I know that lastName is a string, but the equals() method that I am using here, is this the equals() method for a String or the one I've just defined? If it's the latter, I know that I would create a recursive situation, although I'm confident I am using the String equals() yet I want to clarify for completion.

答案1

得分: 3

lastName 是一个 String,因此调用 this.lastName.equals(emp.getLastName()) 将使用 Stringequals 方法实现。当然,对于姓氏的比较也是如此。

英文:

lastName is a String, so calling this.lastName.equals(emp.getLastName()) will use String's implementation of the equals method. The same goes for the comparison of the first names, of course.

答案2

得分: 0

基本上,你重写equals()方法是因为你希望在应用程序中将内存中的两个不同对象视为相等。就像在你的情况下,你创建了两个不同的Employee类对象,如下所示:

Employee emp1 = new Employee("Martinez", "Anthony");
Employee emp2 = new Employee("Martinez", "Anthony");

实际上,这些对象在内存中是两个不同的对象,或者从现实生活的角度来看,它们是两个不同的个体。如果你不重写equals()方法,它将会检查Object类中的equals()方法,其实现如下:

public boolean equals(Object obj) {
     return (this == obj);
}

emp1.equals(emp2)将返回false。

但是可能你的应用逻辑是希望将这两个个体视为相等的,所以在这种情况下,你会重写equals()方法。

在重写equals()时,你可以选择基于什么基准来判断两个个体(员工或对象)是否相等,就像在你的情况下,你选择了firstName和lastName(根据你的要求,你也可以只选择lastName)。

因此,在下面这行代码中,基本上你是在说,如果两个员工的firstName和surName相等,那么将它们视为相等,即使你知道它们是两个不同的个体(内存中的对象):

return this.lastName.equals(emp.getLastName()) && this.firstName.equals(emp.getFirstName());

为此,你在lastName和firstName上调用了String类的equals()方法,这些都是字符串。String类的equals()方法已经被Java库开发人员重写,就像这样:

public boolean equals(Object anObject) {
        if (this == anObject) {
            return true;
        }
        if (anObject instanceof String) {
            String aString = (String)anObject;
            if (coder() == aString.coder()) {
                return isLatin1() ? StringLatin1.equals(value, aString.value)
                                  : StringUTF16.equals(value, aString.value);
            }
        }
        return false;
    }

希望这对你有帮助。

英文:

Basically, you override the equals() method because you want to have two different objects in memory to be considered equal in your application, like in your case you created two different Employee class objects as below :

Employee emp1 = new Employee ("Martinez", "Anthony");
Employee emp2 = new Employee ("Martinez", "Anthony");

These objects are actually two different objects in memory or from a real-life perspective, they are two different individuals and If you will not override equals() , it will check equals() from Object class which has the following implementation :

public boolean equals(Object obj) {
return (this == obj);
}

and emp1.equals(emp2) will return false.

But might be your application logic is such that you want these two Individuals to be considered equal(same), so in that case, you will override the equals() method.

While overriding equals, you can choose on what basis you want two Individuals(employees or objects) to be equal, like in your case you have chosen firstName and lastName(you could have chosen the only lastName as well, depending upon your requirement).

So in the following line, basically you are saying that if two employees firstName and surName are equal then consider them equal,even when you know that they are two different individuals(objects in memory) :

return this.lastName.equals(emp.getLastName()) && this.firstName.equals(emp.getFirstName());

And for that you are calling equals() of String class on lastName and firstName which are Strings.String class has already overridden equals() method by Java library developers like this:

public boolean equals(Object anObject) {
if (this == anObject) {
return true;
}
if (anObject instanceof String) {
String aString = (String)anObject;
if (coder() == aString.coder()) {
return isLatin1() ? StringLatin1.equals(value, aString.value)
: StringUTF16.equals(value, aString.value);
}
}
return false;
}

Hope this was helpful.

huangapple
  • 本文由 发表于 2020年9月28日 04:28:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/64093015.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定