Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How to remove an element from LinkedList while traversing

 
Lim Youjie
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 518
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1840
Eclipse IDE Java Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic