gpt4 book ai didi

java - 我有两个 arrayList,我无法使用 equals() 来正确比较它们。为什么?

转载 作者:行者123 更新时间:2023-12-01 12:24:50 24 4
gpt4 key购买 nike

我有两个arrayLists<myObject> ,其中myObject是我创建的自定义类的对象。我希望能够使用 equals() 比较这些 arrayList方法。

在阅读并寻找答案后,我读到了某些对象,例如 int[]仅被 equals() 视为相等当他们引用相同的东西时,方法。

为了解决这个问题,我尝试重写自定义对象中的 equals 方法。我的对象有 3 个属性(都是基本类型),所以我的 equals 方法现在返回 true如果所有 3 个属性都等于比较对象的属性,否则为 false。但是,比较数组列表仍然不起作用。我做错了什么?

请原谅我解释代码而不是发布它,我这样做是因为变量和名称不是英文的。

编辑:好的,这是代码。 Compra是我的自定义类(class); cantidad , conceptoid是它的属性。

@Override
public boolean equals(Object obj) {
boolean result = true;

if (obj == null) {
result = false;
}else{
Compra comprobada = (Compra) obj;
if(!(this.id == comprobada.getId())){
result = false;
}
if(!(this.cantidad == comprobada.getCantidad())){
result = false;
} if(!this.concepto.equals(comprobada.getConcepto())){
result = false;
}

}
return result;

}

最佳答案

基于此: How can I check if two ArrayList differ, I don't care what's changed

如果您已经实现了自定义对象 equals 正确(您实际上覆盖了它并拥有了自己的对象)并且 arrayList 的大小相同并且每个对象对都相等,那么它将返回 equal。换句话说,您尝试做的事情是完全正确的,但您的 arrayList 实际上并没有按精确的顺序完全相等的对象。

通过执行 System.out.println() 来调查发生的情况,确保在检查集合相等性时调用 equals。如果您不介意,请发送与您的对象相同的内容。

我在一个孤立的示例中运行您的代码并且工作正常(输出 true) - 我改进了 equals 方法,因此它不会执行太多 if 检查,好像只有其中一个不相等,它应该返回 false。

 class stackoverflow {
public static void main(String args[]){
ArrayList<Compra> array1 = new ArrayList<>();
ArrayList<Compra> array2 = new ArrayList<>();
array1.add(new Compra(1,2,"test"));
array2.add(new Compra(1,2,"test"));
System.out.println(array1.equals(array2));
}
}
class Compra {
int id;
int cantidad;
String concepto;

public Compra(int id, int cantidad, String concepto){
this.id = id;
this.cantidad = cantidad;
this.concepto = concepto;
}



public boolean equals(Object obj) {


if (obj == null) {
return false;
}else{
Compra comprobada = (Compra) obj;
if(!(this.id == comprobada.getId())){
return false;
}
if(!(this.cantidad == comprobada.getCantidad())){
return false;
}
if(!this.concepto.equals(comprobada.getConcepto())){
return false;
}

}
return true;
}



public int getId() {
return id;
}




public int getCantidad() {
return cantidad;
}




public String getConcepto() {
return concepto;
}


}

一些需要检查的事情:

  • 您确定不更改 ArrayList 中内容的顺序吗?:
  • 您是否进行打印以确保发生这些等于检查并按预期返回 true 或 false?
  • 您确定概念字符串完全相同、大小写相同且不包含多余空格等吗?

关于java - 我有两个 arrayList<myObject>,我无法使用 equals() 来正确比较它们。为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26445705/

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