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

时间:2014-02-11 16:45:03

标签: java equals

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

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

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");

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

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

6 个答案:

答案 0 :(得分:8)

您应该已经包含了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));
}

输出

false
true

答案 1 :(得分:3)

由于Java使用隐式引用,您需要在对象euqality和引用euqality之间做出区别。

如果你只是想知道两个对象是否同一个内存单元,那么它们实际上是相同的,你可以使用equals运算符:

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

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

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

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

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

Object A = new Fruit("A");
Object B = new Fruit("A");
System.out.println(A.equals(B));
在这种情况下,

应该返回true。

为了达到这个目的,你可以为你可以编写的每个可能的类使用以下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;
}

您必须为班级的每个字段执行boolean flag = this.getA().equals(B.getA());。 如果对象字段具有相同的值,则会导致相等。

但是oyu必须记住,没有完美的平等方法。在java中有所谓的哈希码等于契约,这意味着只要A.equals(B)

A.hashCode()==B.hashCode()必须保持

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

答案 2 :(得分:0)

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

答案 3 :(得分:0)

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

然后在你的equals方法中:

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

答案 4 :(得分:0)

这个怎么样,简单易行:

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

答案 5 :(得分:-1)

您应该比较传递给构造函数的String值

,而不是检查实例