wood burning stoves*
The moose likes Java in General and the fly likes How to remove an element from LinkedList while traversing Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Java 8 in Action this week in the Java 8 forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "How to remove an element from LinkedList while traversing" Watch "How to remove an element from LinkedList while traversing" New topic
Author

How to remove an element from LinkedList while traversing

Lim Youjie
Greenhorn

Joined: Dec 27, 2004
Posts: 22
Hi,

May I know whether there is any way to remove an element in a LinkedList while I was traversing through it?

I have tried it and was prompt NullPointerException.
Scott Johnson
Ranch Hand

Joined: Aug 24, 2005
Posts: 518
You can remove elements from a LinkedList while iterating through the list by calling Iterator.remove().

Post your code and we may be able to help further.
Lim Youjie
Greenhorn

Joined: Dec 27, 2004
Posts: 22
Hmm my code is as below:

There is a linkedlist inside another linkedlist.

//Eliminate path that are long
while (iterator.hasNext())
{
BoardState boardstate = (BoardState) iterator.next();
LinkedList path = (LinkedList) boardstate.path;
Puzzle puzzle = (Puzzle) path.getLast();
int levelCount = boardstate.getLevel(puzzle);

ListIterator iterator2 = searchQueue.listIterator();

while (iterator2.hasNext())
{
BoardState boardstate2 = (BoardState) iterator2.next();
LinkedList path2 = (LinkedList) boardstate2.path;
Puzzle puzzle2 = (Puzzle) path2.getLast();
int levelCount2 = boardstate2.getLevel(puzzle2);

if (puzzle.equals(puzzle2))
{
if (levelCount >= levelCount2)
{
iterator.remove();
}
else
{
iterator2.remove();
}
}
}
}
Joel McNary
Bartender

Joined: Aug 20, 2001
Posts: 1815
Aargh. This makes my head hurt.

I typically create a List of Objects To Remove, and after I'm done iterating, call .removeAll(objectsToRemove) on my source collection. It prevents me from getting headaches.

What line were you getting the NullPointer exception on?

BTW, use [CODE] and [/CODE] tags, not [QUOTE] and tags -- the CODE tags preserve the formatting of your code.
[ July 20, 2006: Message edited by: Joel McNary ]

Piscis Babelis est parvus, flavus, et hiridicus, et est probabiliter insolitissima raritas in toto mundo.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: How to remove an element from LinkedList while traversing
 
Similar Threads
Vector operation implementation why JDK preferred arrays over linkedlist
Q about ArrayList/LinkedList
a simple problom
a simple but complex problom
Remove an element from array by index