list.removeAll(otherList) - wrong result

Hi guys,

I have 2 Lists:

1.carList

2.documentList

*both contain the same type: car PLUS I have overloaded the hashCode and equals of car

carList has 1106 items

documentList has 88 items

I would like to remove the 88 items of documentList from the carList.

(simple math: 1106-88=1018)

By doing this:

(1)

this.carList.removeAll(documentList);

the carList.size() = 1013 (?!?!)

by doing this:

(2)

for (int x=carList.size()-1; x>=0; x--)

{

Car cx = (Car) carList.get(x);

for (int i=documentList.size()-1; i>=0; i--)

{

Car ci = (Car) documentList.get(i);

if (cx.equals(ci))

{

carList.remove(x);

documentList.remove(i);

break;

}

}

}

I get 1018 (correct)

Question: Why am I getting the wrong result in option 1? (once again, I have overloaded the hashCode and equals of car)

[1317 byte] By [xianwinwina] at [2007-11-26 16:51:35]
# 1
Have you looked to see what the differences are between the two approaches?
Tillermana at 2007-7-8 23:19:18 > top of Java-index,Java Essentials,Java Programming...
# 2
removeAll(Collection c) Removes from this list all the elements that are contained in the specified collection http://java.sun.com/j2se/1.4.2/docs/api/java/util/List.html
xianwinwina at 2007-7-8 23:19:18 > top of Java-index,Java Essentials,Java Programming...
# 3
Yes, I know what the method does, what I asked was by looking at how the results differ could you identify any pattern that may point to why the problem occurred in the first place.
Tillermana at 2007-7-8 23:19:18 > top of Java-index,Java Essentials,Java Programming...
# 4
No, I was expecting to get the same result. I didn't find the 5 (1018-1013=5) cars since Option II gave me the correct answer, I just wonder why the first one is incorrect.
xianwinwina at 2007-7-8 23:19:18 > top of Java-index,Java Essentials,Java Programming...
# 5
Any chance that carList contains duplicates? They'd be removed by removeAll, but not by your second example.
doremifasollatidoa at 2007-7-8 23:19:18 > top of Java-index,Java Essentials,Java Programming...
# 6

I am going to guess - and it is a guess - that it is down to the way the removeAll() method works 'under the covers' so to speak. Like you, I cannot think of any reason why the results should differ given that I would expect the equals() method - which you overrode - that would be called upon most. Sorry I cannot help any further.

Tillermana at 2007-7-8 23:19:18 > top of Java-index,Java Essentials,Java Programming...