Reputation: 7403
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;
}
The code that does the subtraction:
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;
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.
Upvotes: 1
Views: 7632
Reputation: 16190
Plain answer (Assuming you mean Apache Commons Collections): According to the source code of ListUtils.subtract(List, List)
it uses ArrayList.remove(Object)
which in turn uses equals()
to determine the items to delete.
To your problem: My guess would be to look into the equals method. Is the one you are providing really called? Are the dependent methods (for Manufacturer etc.) correct?
Upvotes: 3
Reputation: 2939
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.
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.
Upvotes: 1