• Post Reply Bookmark Topic Watch Topic
  • New Topic

for construct when using an iterator  RSS feed

 
Mohammed Azeem
Ranch Hand
Posts: 56
3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,

I am studying the Java Collections Framework. There's a snippet of code for which I need clarification, otherwise it will dwell in my mind and I won't be able to move on!

I understand the code and its purpose but can't decide how the for - construct should be "read out aloud" in words.

Here's the snippet:

static void filter(Collection<?> c) {
for (Iterator<?> it = c.iterator(); it.hasNext(); )
if (!cond(it.next()))
it.remove();
}

for (Iterator it<?> it = c.iterator(); it.hasNext();) ---> how should this line be read in words, it doesn't fit the syntax of a for-loop or a for-each loop.


As always, all help much appreciated.

Mohammed.
 
Junilu Lacar
Sheriff
Posts: 11165
160
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yeah, this one is a little tricky. I would ignore the "for" part and read it out loud as "While the iterator for collection c has another element, do the following: ... "

BTW, reading code out loud is an EXCELLENT way to understand a program better -- it's a strategy that I often recommend.
 
Junilu Lacar
Sheriff
Posts: 11165
160
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A couple of things: please UseCodeTags (← click that link) when you post code.

The implementation you showed is not a very good one. See the API documentation for Iterator.remove() for a couple of potential issues. The other thing too is that the cond() method is external to this method.

The Java 8 Stream.filter and Predicate functional interface provide a better way to implement a filter. The filter condition is passed in to the filter method which returns anything that meets the filter condition.
 
Mohammed Azeem
Ranch Hand
Posts: 56
3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Junilu, it makes sense to think of it as a "while".

Great. I think I can mark this as solved.


 
Mohammed Azeem
Ranch Hand
Posts: 56
3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
And yes, cond() would be a user defined method that would test the element returned by it.next() against some filtering condition.

OK now I can move on. Thanks for pointing out the alternatives.


 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!