有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

我试图实现一个Java类,它包含来自另一个类的两个对象引用。 i、 我有两门课。类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的两个实例。希望这更清楚,再次抱歉


共 (1) 个答案

  1. # 1 楼答案

    我想你的意思是

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