Java 如何检查2个类实例是否相同

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21707840/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 10:11:34  来源:igfitidea点击:

How to check if 2 Class instances are the same

javaequals

提问by kar

For example I have a class Fruit. I create 2 instances:

例如我有一个水果类。我创建了 2 个实例:

Fruit apple = new Fruit("apple");
Fruit orange = new Fruit("orange");

The value of the 2 instances are not the same thus I am looking for the answer to be false. I override the .equals() method and wrote the following method to do the test:

2 个实例的值不相同,因此我正在寻找错误的答案。我重写了 .equals() 方法并编写了以下方法来进行测试:

@Override
public boolean equals(Object otherObject){
    if(otherObject instanceof Fruit){ 
        return true;
    }
    return false; 
}

    if(apple.equals(orange))
        System.out.println("true"); 
    else
        System.out.println("false");

The above method gives me the answer as true. From my understanding, this is a correct response since this simply tests if they both belongs to the same Class which is true.

上述方法给了我正确的答案。根据我的理解,这是一个正确的响应,因为这只是测试它们是否属于同一类,这是真的。

But I can't get around to testing the values of the instances itself. Please advice. Thanks.

但是我无法测试实例本身的值。请指教。谢谢。

采纳答案by Elliott Frisch

You should have included your Fruitclass, but here is one way

您应该包含您的Fruit课程,但这是一种方法

static class Fruit {
  private String name;

  public Fruit(String name) {
    this.name = name;
  }

  @Override
  public boolean equals(Object otherObject) {
    // check for reference equality.
    if (this == otherObject) {
      return true;
    }
    if (otherObject instanceof Fruit) {
      Fruit that = (Fruit) otherObject;
      // Check for name equality.
      return (name == null && that.name == null)
          || name.equals(that.name);
    }
    return false;
  }
}

public static void main(String[] args) {
  Fruit apple = new Fruit("apple");
  Fruit apple2 = new Fruit("apple");

  Fruit orange = new Fruit("orange");

  if (apple.equals(orange))
    System.out.println("true");
  else
    System.out.println("false");

  // You can also use the shorter
  System.out.println(apple.equals(apple2));
}

Outputs

输出

false
true

回答by bluedevil2k

@Override
public boolean equals(Object otherObject){
    if(!otherObject instanceof Fruit){ 
        return false;
    }
  return ((Fruit)otherObject).getName().equals(name);
}

回答by floppy12

Let's say that "apple" is stored as the name of your Fruit (as a member String m_name for example)

假设“apple”存储为您的 Fruit 的名称(例如作为成员 String m_name)

Then in your equals method:

然后在你的 equals 方法中:

if( otherObj instanceof Fruit
 && (Fruit)otherObj.name.equals(this.name))
return true;
else 
return false;

回答by grepit

How about this, simple and easy :

这个怎么样,简单易行:

public boolean check(Object ObjectOne, Object ObjectTwo) {
    return ObjectOne.getClass() == ObjectTwo.getClass();
}

回答by nesreka

As Java uses implicit references you need to make a difference between object euqality and reference euqality.

由于 Java 使用隐式引用,因此您需要区分对象等同性和引用等同性。

If you just want to know wether two objects denode the same memory cell, so they are really the same, you cann use the equals operator:

如果你只是想知道两个对象是否对同一个内存单元进行 denode,所以它们真的是一样的,你可以使用 equals 运算符:

Object A = new Fruit("A");
Object B = new Fruit("A");
System.out.println(A == B);

This would print false, as A and B are not the same reference cell.

这将打印错误,因为 A 和 B 不是相同的参考单元格。

Object A = new Fruit("A");
Object B = A
System.out.println(A == B);

Would return true, as they both are "pointers" to the same reference cell.

将返回 true,因为它们都是指向同一引用单元格的“指针”。

If you want to achieve semantic equality, I would advise you to make use of the equals method AND the fields of the class.

如果你想实现语义相等,我建议你使用 equals 方法和类的字段。

Object A = new Fruit("A");
Object B = new Fruit("A");
System.out.println(A.equals(B));

should return true in this case.

在这种情况下应该返回 true。

To achieve this you can usethe following equals method for every possible class you could write: (assuming you have getter and setter for the field A and your class is named myClass)

为了实现这一点,您可以对您可以编写的每个可能的类使用以下 equals 方法:(假设您有字段 A 的 getter 和 setter,并且您的类名为 myClass)

public boolean equals(Object B){
if(B instanceof MyClass){
  MyClass B = (MyClass) B;
  boolean flag = this.getA().equals(B.getA());
  return flag;
}
  return false;
}

You would have to do the boolean flag = this.getA().equals(B.getA());for every field of the class. This would lead to equality if the objects fields have the same values.

您必须为boolean flag = this.getA().equals(B.getA());班级的每个领域都做。如果对象字段具有相同的值,这将导致相等。

But oyu have to keep in mind, that there is no perfect equals method. There is the so called hashcode equals contract in java which means that A.equals(B)has to hold, whenever A.hashCode()==B.hashCode()

但是 oyu 必须记住,没有完美的 equals 方法。java中A.equals(B)有所谓的哈希码等于合同,这意味着必须持有,无论何时A.hashCode()==B.hashCode()

A nice thing of the flag approach is that you don't have to care about the types of the objects fields, as for Basic Types that are not Objects (int, float, ...) the Java Runtime will do implicit bocing and cast them to Integer or Float Objects and use the equals method of them.

标志方法的一个好处是您不必关心对象字段的类型,至于不是对象(int、float 等)的基本类型,Java 运行时将执行隐式 bocing 和强制转换将它们转换为 Integer 或 Float 对象并使用它们的 equals 方法。