• Post Reply Bookmark Topic Watch Topic
  • New Topic

Question about cycling through hasmap keys  RSS feed

 
Joseph Tulowiecki
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
ok, I'm confused. I'm trying to use the iterator interface.

I have a hashmap and I'm using Iterator i = hashmap.keySet().iterator() then I use the iterator in while loop instead of a for loop because depending on the situation, sometimes the i need to break the while loop before it is done iterating through this while loop. It is a multi conditional while loops.. like while((i.hasNext) & (sum < 30)) for example. Say the sum his 32, then it kicks out of the while loop. However I need to call this method over and over again in my program. It works the first time I call it but the second time I get a java.util.NoSuchElementException at java.util.HashMap$HashIterator.nextEntry(HashMap.java:809). What i've been doing is just saying Iterator it = hashmap.keySet().iterator() every time i enter the method but when I'm guessing here is that this means nothing because I'm not using the "new" keyword so i't's not resetting. I obviously can't do this because it is an interface so how can I use this method multiple times? If I use an iterator, I can only use it once? If I can't use an iterator in a while loop. then how else would I cycle through the hashmap. I'll post some code below but I don't know how much sense it will make.

 
James Boswell
Bartender
Posts: 1051
5
Chrome Eclipse IDE Hibernate
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Joseph

The code you have posted is not very helpful for people trying to help you.

Could you post the specific while loop causing you the problem and also where the Iterator instance is declared and initialized.

Cheers
 
Joseph Tulowiecki
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi James. Thanks, I was wondering why I wasn't getting any responses. I will keep that in mind next time. For this issue, I just figured out the problem though. It was a mistake in the recursive algorithm. There was one specific instance where iterator.next() was being called when it shouldnt have been. Thanks for your time though. ^^
 
Campbell Ritchie
Marshal
Posts: 56600
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Joseph Tulowiecki wrote:. . . I was wondering why I wasn't getting any responses. . . .
Probably because you weren’t patient enough. You had a response in 2 hours 22 minutes, early on Sunday morning.

Are you using the same Iterator again when you re-enter the loop? If so, you start where you left off, which won’t work well. you should always use a new Iterator for each loop. Also make sure your Iterators are local variables which go out of scope at the end of the loop.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!