简体   繁体   English

关于在实现等于对象以比较Java中的对象时使用此方法

[英]regarding using this in implementing equals for comparing objects in Java

I saw a code segment regarding defining equals , from another question thread in this forum. 我从该论坛的另一个问题线程中看到了有关定义equals的代码段。 But my question is what does the following code does, and why it is needed? 但是我的问题是以下代码做什么,为什么需要它? Thanks. 谢谢。

   if (obj == this)
   {
       return true;
   }

The original code is shown as follows. 原始代码如下所示。 http://stackoverflow.com/questions/8338326/what-does-equalsobject-obj-do#

public boolean equals(Object obj)
{
if (obj == this)
{
    return true;
}
if (obj == null)
{
    return false;
}
if (obj instanceof Contact)
{
    Contact other = (Contact)obj;
    return other.getFirstName().equals(getFirstName()) &&
            other.getLastName().equals(getLastName()) &&
            other.getHomePhone().equals(getHomePhone()) &&
            other.getCellPhone().equals(getCellPhone());

}
else
{
    return false;
}

} }

Implementing the equals method of a Java class is an often discussed topic. 实现Java类的equals方法是一个经常讨论的话题。 In general you want to ensure, that the method returns true , if: 通常,您需要确保在以下情况下该方法返回true

  • the object you compare this with is the same object regarding the pointer (object == this) or 您与this进行比较的对象是关于指针的相同对象(对象==此)或
  • the object you compare this with is the same regarding your domain 您与this进行比较的对象关于您的域是相同的

So regarding your question, you ask for the former case, in which Java just checks if the object passed and this are pointing to the same address in memory (maybe this link helps you http://www.javaworld.com/article/2072762/java-app-dev/object-equality.html ). 所以,关于你的问题,你问前者的情况下,其中的Java刚刚检查,如果object通过, this是指向内存中(也许这个链接可以帮助你在同一地址http://www.javaworld.com/article/2072762 /java-app-dev/object-equality.html )。

A short note: When you implement the equals method you normally follow this pattern: 简短说明:实现equals方法时,通常遵循以下模式:

  1. check if you have the same object (regarding pointers), ie 检查您是否具有相同的对象(关于指针),即

     if (object == this) return true; 
  2. you make sure that you don't have any null instance (to avoid further NullPointerException and if it's null it can never be equal, ie, 您要确保没有任何null实例(为避免进一步的NullPointerException ,如果它为null则它永远不能相等,即,

     else if (object == null) return false; 
  3. you check if the object is equal regarding whatever equal means in your domain (eg, a dao might be assumed to be equal if the id is equal); 您检查对象在域中是否相等,是否相等(例如,如果id相等,则可以假定dao相等); prior to doing the domain specific validation, you normally always make sure that you have an object of the correct instance, ie, 在进行特定于域的验证之前,通常请务必确保您拥有正确实例的对象,即

     else if (this.getClass().equals(obj.getClass()) { ... } 

    or 要么

     else if (this.getClass().isInstance(obj.getClass()) { ... } 
  4. in all other cases you want to return false, ie, 在其他所有情况下,您都想返回false,即

     else return false; 

NOTE: When implementing the equals method it is often useful to use the Objects.equals(...) method to compare the different attributes of the instances. 注意:在实现equals方法时,通常使用Objects.equals(...)方法来比较实例的不同属性。

EXAMPLE: 例:

@Override
public boolean equals(final Object obj) {
    if (obj == this) {
        // we have the same object regarding the pointers (e.g., this.equals(this)), or have a look at 'Manjunath M' post for a different example
        return true;
    } else if (obj == null) {
        // we compare with null (e.g., this.equals(null))
        return false;
    } else if (Contact.class.isInstance(obj.getClass())) {
        /*
         * If you want to be more strict you could also use:
         * getClass().equals(obj.getClass())
         */
        Contact other = Contact.class.cast(obj);
        return Objects.equals(other.getFirstName(), getFirstName()) &&
                Objects.equals(other.getLastName(), getLastName()) &&
                Objects.equals(other.getHomePhone(), getHomePhone()) &&
                Objects.equals(other.getCellPhone(), getCellPhone());
    } else {
        return false;
    }
}

'==' in Java is used for comparing the references of objects. Java中的'=='用于比较对象的引用。 If the object is compared with own self then equals function must return true. 如果将对象与自己的自身进行比较,则equals函数必须返回true。 That's why this condition is added in equals method. 这就是为什么将此条件添加到equals方法中的原因。

for primitive datatypes like int,char '==' this compares values and for objects it compares there references. 对于像int,char'=='这样的原始数据类型,它比较值,对于对象,它比较那里的引用。 Some literature says that working of '==' is really weired as comparing references is not really important. 一些文献说,'=='的工作确实很奇怪,因为比较引用并不是很重要。

this refer's to the same object inside which the if statement is. 是指if语句所在的同一对象。 By comparing the obj== this it checks if the object passed is the object itself inside which the equals function is called. 通过比较obj ==,它检查传递的对象是否是内部调用equals函数的对象本身。

you can check this question too: What is the meaning of "this" in Java? 您也可以检查这个问题: Java中“ this”的含义是什么?

If you are not overriding the equals method in your respective class it executes the implementation that already written in the equals method in Object class(The super most class for all the classes) there they are checking the equality like this 如果您没有在各自的类中覆盖equals方法,它将执行已经在Object类(所有类的最高级类)的equals方法中编写的实现,在那里,他们正在检查这种相等性

obj == obj1

the code mentioned above is actually checks the equality based on the memory location address that those two objects where they are created, thus above line checks whether two objects that we are trying to check equality have same reference or not. 上面提到的代码实际上是根据创建两个对象的内存位置地址检查是否相等,因此,上面的代码行检查我们尝试检查相等性的两个对象是否具有相同的引用。 If both have same reference we don't have to do any more circus for checking equality. 如果两者都具有相同的引用,则我们无需再做任何杂技检查相等性。 like this 像这样

Car car = new Car();
Car car1 = car;

car.equals(car1);

As you can clearly see that car and car1 have same reference means both are same object having same memory address. 您可以清楚地看到car和car1具有相同的引用方式,它们都是具有相同存储地址的相同对象。 Thus don't have to check for the equality by checking attributes.it just avoids execution extra code. 因此不必通过检查属性来检查相等性,它只是避免执行额外的代码。

this refers to the class's object under which the equals function is being executed. this是指在其下执行equals函数的类的对象。 If obj is the other object that needs to be compared for equality and obj and this refer to the same instance then they are true, right? 如果obj是为了进行比较,以平等,需要其他物体objthis指的是相同的实例,然后他们是真的吧?

For example 例如

MyClass myObject = new MyClass();
myObject.equals(obj);

In this case both this and obj in the equals method would refer to the same instance myObject . 在这种情况下,equals方法中的thisobj都将引用同一实例myObject In such cases we don't need to check other properties of these objects for equality. 在这种情况下,我们不需要检查这些对象的其他属性是否相等。

TL;DR - Checking for such case helps in optimization as this avoids extra work needed to check the two objects for equality. TL; DR-检查这种情况有助于优化,因为这避免了检查两个对象是否相等所需的额外工作。

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

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