比较包含两个其他对象引用的对象

问题描述 投票:0回答:1

我试图实现一个Java类,其中包含两个来自另一个类的对象引用,即我有两个类。基本上,我试图将一对对象与另一对对象进行比较,只有当这两对对象相同时,才用一个方法返回true。我似乎只能比较内存中的位置,而不是比较对象本身。

为我的含糊不清道歉!这是我创建基本对象的类。

public class B {

String name;
int number;

B(String name, int number) {
    this.name = name;
    this.number = number;
}

而这里是我创建和对象的类,包含两个类b的对象引用。

public class A{

Object one;
Object two;

A(Object one, Object two) {
    this.one = one;
    this.two = two;
}

类b的对象被调用。

B bob = new B("Bob", 22);
B bobby = new B("Bobby", 22);
B robert = new B("Robert", 32);

A类的对象被调用

A firstPair = new A(bob,bobby);
A secondPair = new A(bobby,robert);

所以我的问题是重写equals()方法来比较A类的两个实例. 希望这更清楚,再次抱歉!

java
1个回答
2
投票

我猜测你的意思是

class A{
    private B b1;
    private B b2;
}

A a1 = new A();
A a2 = new A();

你想看看a1和a2是否相同。

要做到这一点,在A类和B类中添加覆盖等价物

class B{
    public boolean equals(B that){
         //compare their attributes (what makes 2 B equals)
         return this.name.equals(that.b) && this.number == that.number;
    }
}

class A{
    private B b1;
    private B b2;
   public boolean equals(A anotherA){
      return b1.equals(anotherA.b1) && b2.equals(anotherA.b2); // (A is equal if both b1 and b2 are equal)
   }
}
© www.soinside.com 2019 - 2024. All rights reserved.