本文介绍了ListUtils.subtract() 如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to subtract the values of one list from another with the ListUtils.subtract(1,2) however I noticed that the subtraction never occurs so I keep getting all the elements in 1 returned. I thought this might be indicative of an equality issue but my hashcode and equals method are fine.(I think)

   @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 中减去受影响的值(返回 allcars 集),这让我认为由于某种原因,equals 方法可能是错误的.

I have inspected both lists and they're fine, I however can't get ListUtils to subtract affected from allcars (returns the allcars set) leading me to think for some reason the equals method could be wrong.

推荐答案

getManufacturer() 返回一个制造商,并且您没有在那里覆盖 .equals 和 .hashCode,因此两个具有相同字段的制造商实例不会被视为相等.

getManufacturer() returns a Manufacturer, and you haven't overridden .equals and .hashCode there, so two Manufacturer instances with identical fields will not be counted as equal.

这是基于来自 IRC 的额外上下文,因此请将其添加到您的问题中,以便对其他人有用.一般规则是,如果使用测试用例,您会更快得到准确答案.

This is based on extra context from IRC, so please add that to your question so that it's useful for others. The general rule is that with a test case you would have got an accurate answer sooner.

这篇关于ListUtils.subtract() 如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-16 10:18