Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Moving Linked List Items 1

Status
Not open for further replies.

SlykFX

Programmer
Oct 12, 2002
76
GB
Can someone point out where im going wrong here please.

ive got my linked list populated with several objects, and im trying to move the selected object to the front of the list (or the back depending on which direction its supposed to go)

what i have so far is:
Code:
public void toFront()
{
    Iterator it = theObjects.iterator();
    while (it.hasNext())
    {
        Object tmpObject = (Object)it.next();
        if (tmpObject.isSelected())
        {
            theObjects.addFirst(tmpObject);
            // theObjects.addLast(tmpObject); in toBack()
            it.remove();
        }
    }
}

the error that it drops when this is called is:
java.util.ConcurrentModificationException
at java.util.LinkedList$ListItr.checkForComodification(LinkedList.java:552)
at java.util.LinkedList$ListItr.remove(LinkedList.java:521)
...

i have tried swapping the .remove and .addFirst/.addLast lines around but to no avail.
i have also tried .addFirst(it.next());/.addLast(it.next()); but not prospered there

the error seems to be in the .addFirst/.addLast line as if this is commented out, the object is removed, if i comment out the .remove() line the same error shows its face

any advice greatly appreciated

thanks in advance

I can't be bothered to have a sig!
 
Think about Objects C D E, D is selected.
Now you like to get D C D E -> D C E?

In step 2, (D C D E), the collection is modified, and the iterator is out of sync.
Code:
    Object tmpObject = null; 
    while (it.hasNext())
    {
        tmpObject = (Object)it.next();
        if (tmpObject.isSelected())
        {
            it.remove();
        }
    }
    if (tmpObject != null) theObjects.addFirst(tmpObject);
    // theObjects.addLast(tmpObject); in toBack()

seeking a job as java-programmer in Berlin:
 
ahhhhh, it all makes sense now

thanks loads for that :)

I can't be bothered to have a sig!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top