Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove element From Linked Hash Set in java?

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?

like image 700
sar Avatar asked Feb 07 '26 21:02

sar


2 Answers

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.
like image 152
Masudul Avatar answered Feb 09 '26 12:02

Masudul


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();
...
like image 22
Thomas Avatar answered Feb 09 '26 12:02

Thomas