gpt4 book ai didi

java - 为什么 '==' 和 .equals() 方法的 java 对象比较都失败了?

转载 作者:行者123 更新时间:2023-11-29 08:20:27 24 4
gpt4 key购买 nike

我正在使用 == 和 equals() 方法比较相同的对象,但它们都失败了。我尝试了以下四种组合。请有人指导我哪里出错了。

public class Question {

int rollNo;
String name;

Question(int rollNo, String name) {
this.rollNo = new Integer(rollNo);
this.name = new String(name);
}

public int getRollNo() {
return new Integer(rollNo);
}

public void setRollNo(int rollNo) {
if(rollNo>0) this.rollNo = rollNo;
}

public String getName() {
return new String(name);
}

public void setName(String name) {
if(name!=null) this.name = name;
}

public static void main(String[] args) {
Question obj1 = new Question(123, "Student1");
Question obj2 = new Question(123, "Student1");
Question obj3 = new Question(456, "Student2");

// All if conditions are evaluating to false
if(obj1 == obj2) System.out.println("Equal objects 1 and 2 using ==");
if(obj1.equals(obj2)) System.out.println("Equal objects 1 and 2 using equals()");
if(obj1 == new Question(123, "Student1")) System.out.println("Equal objects 1 and 2 using == and new");
if((new Question(123, "Student1")).equals(obj2)) System.out.println("Equal objects 1 and 2 using equals() and new");
}

我也欢迎对我的代码质量提出建议,因为我刚刚开始编码。

最佳答案

== 失败,因为 Question 对象是不同的对象。 (引用类型的 == 运算符测试引用是否针对同一对象。)

它因 equals 而失败,因为您正在使用 Object::equals(Object) 方法。该方法指定==具有相同的含义。

如果您希望 Question::equals(Object) 表现不同,您需要覆盖通过添加像这样的方法:

    @Override
public boolean equals(Object other) {
// implement this according to the spec to give the equality
// semantics you need
}

实际的实现可能是这样的:

    @Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj instanceof Question) {
Question other = (Question) obj;
return this.rollNo == other.rollNo &&
this.name.equals(other.name);
} else {
return false;
}
}

我注意到您的代码中存在一些其他问题。例如:

    Question(int rollNo, String name) {
this.rollNo = new Integer(rollNo);
this.name = new String(name);
}
  1. 构造函数应该是public
  2. 由于 this.rollNo 被声明为 int,创建一个 Integer 并赋值是毫无意义的……而且效率低下。将会发生的是 Integer 将被拆箱以获取其值,然后该对象将被丢弃。只需将 rollNo 分配给 this.rollNo
  3. 如果您确实需要显式获取Integer实例,正确的方法是使用Integer.valueOf (整数)。这利用了 Integer 对象的内置缓存。
  4. new String(name) 创建一个字符串是不必要的,而且效率低下。字符串是不可变的。没有必要复制它们。当然,不在这里。

关于java - 为什么 '==' 和 .equals() 方法的 java 对象比较都失败了?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59332668/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com