I am trying to write a very simple method to remove duplicates in a LinkedList:
I try to do this without using additional buffer, so I maintain two iterators on the linked list, one does the normal iteration, and another iterates through all prior nodes to check for dupes (as indicated in CareerCup); however, the compiler tells me there is a CME even though I am calling itr1.remove():
public static void RemoveWithoutBuffer(LinkedList l) {
ListIterator itr1 = l.listIterator();
int count1 = 0;
int count2 = 0;
while (itr1.hasNext()) {
Object next = itr1.next();
count1++;
count2 = 0;
ListIterator itr2 = l.listIterator();
while (itr2.hasNext()) {
count2++;
if (count2 == count1)
break;
if (itr2.next() == next){
itr1.remove();
}
}
}
}
Another simpler solution of this problem with the aid of hashset is easy as follows, and no exception reported:
public static void Remove(LinkedList l) {
HashSet set = new HashSet();
ListIterator itr = l.listIterator();
while (itr.hasNext()) {
Object next = itr.next();
if (set.contains(next))
itr.remove();
else
set.add(next);
}
}
Is it because when I am iterating through itr2 I cannot modify on itr1? Is there a way to fix this? Thank you guys.
In the first case yes – you’re altering the collection’s contents via iterator2, while iterator1 is not aware about the changes. In the second case HashSet/HashMap don’t allow removing elements while iterating through them.
You can add removed elements to another collection, and removeAll them after an iteration. E.g.
I hope it helps.
P.S. more details on how to remove elements from list, concerning algorithm complexity you can read here Removing ArrayList object issue