比较包含另外两个对象引用的对象



我正在尝试实现一个Java类,该类包含来自另一个类的两个对象引用。即我有两节课。类A的一个实例包含来自类B的两个实例。基本上,我试图将一对对象与另一对对象进行比较,方法只有在两对对象相同时才返回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的两个实例。希望这更清楚,再次抱歉!

我想你的意思是

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)
}
}

最新更新