I want to know Different ways to remove element from Linked Hash Set. I tried following code
LinkedHashSet<String> lhs = new LinkedHashSet<String>();
for(int i=0;i<10;i++)
lhs.add(String.valueOf(i));
Iterator<String> it=lhs.iterator();
System.out.println("removed?=="+lhs.remove("1"));
while(it.hasNext())
{
System.out.println("lhs"+it.next());
}
i got following output
removed?==true
Exception in thread "main" java.util.ConcurrentModificationException
at java.util.LinkedHashMap$LinkedHashIterator.nextEntry(Unknown Source)
at java.util.LinkedHashMap$KeyIterator.next(Unknown Source)
at preac.chapter1.Start.main(Start.java:321)
What i miss? thanks in advance.
P.S I have also tried iterator.remove() method but got Illegal State Exception
EDIT
I just came to know i have to use iterator remove method. then what it is use of Link Hash Set remove method ? In which cases we should use this method?
Try to remove element using Iterator.remove like below,
LinkedHashSet<String> lhs = new LinkedHashSet<String>();
for (int i = 0; i < 10; i++) {
lhs.add(String.valueOf(i));
}
Iterator<String> it=lhs.iterator();
// System.out.println("removed?=="+lhs.remove("1"));
while(it.hasNext()) {
String value=it.next();
if("1".equals(value)){
it.remove();
}
else{
System.out.println("lhs "+value);// Print the other value except 1
}
}
System.out.println(lhs);// After remove see the result here.
You get the exception because the iterator realizes that you called remove after creating the iterator (using an internal modification counter).
Let's assume add and remove increment the modification counter by 1.
When the iterator is created, it sees a modification counter of 10.
However, when the iterator is first accessed, the modification counter is 11, due to the call to remove, hence the exception.
Switch the statements and it should be fine:
...
System.out.println("removed?=="+lhs.remove("1"));
Iterator<String> it=lhs.iterator();
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With