gpt4 book ai didi

java - ListUtils.subtract() 如何工作?

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

我正在尝试使用 ListUtils.subtract(1,2) 从另一个列表中减去一个列表的值,但是我注意到减法从未发生,所以我一直在返回 1 中的所有元素。我认为这可能表明存在平等问题,但我的哈希码和 equals 方法没问题。(我认为)

   @Override
public boolean equals(Object o) {
if(!(o instanceof Car))
return false;

Car ct = (Car) o;

return this.getManufacturer().equals(ct.getManufacturer())
&& this.getImmat().equals(ct.getImmat())
&& this.getModel().equals(ct.getModel());
}

@Override
public int hashCode() {
int hash = 5;
hash = 71 * hash + (this.model != null ? this.model.hashCode() : 0);
hash = 71 * hash + (this.immat != null ? this.immat.hashCode() : 0);
hash = 71 * hash + (this.manufacturer != null ? this.manufacturer.hashCode() : 0);
return hash;
}

做减法的代码:

            List <Car> affected = new LinkedList<Car>();

for(Driver c : tmp)
affected.add(c.getCar());

List <Car> allcars = carDAO.findAllCars("order by model");//returns every car

List<Car> cars = ListUtils.subtract(allcars, affected );


return cars;

我已经检查了两个列表,它们都很好,但是我无法让 ListUtils 从 allcars 中减去 affected(返回 allcars 集)导致我出于某种原因认为 equals 方法可能是错误的。

最佳答案

简单的答案(假设你的意思是 Apache Commons Collections):根据 ListUtils.subtract(List, List) 的源代码,它使用 ArrayList.remove(Object)它又使用 equals() 来确定要删除的项目。

针对您的问题:我的猜测是研究 equals 方法。你提供的那个真的叫吗?依赖方法(对于制造商等)是否正确?

关于java - ListUtils.subtract() 如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9073120/

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