I’m a little confused about iterators in Java. How do I make next() only return certain values? Like say I have a boolean array of 10 elements, and I only want to return those that are true. Do I put a conditional in the next() method that checks for that condition and returns when it is met? Or do I check for the condition when I actually use the iterator and keep calling next() until I get a suitable value, and then use that value?
Similarly if I have an array of ints, and I want to create a string representation of the array where each element is separated by a space, but I only want to use negative elements. If I want to do this with an iterator, do I check for the negative element in the next() method and only return next values that are negative, or do I check when I’m making the string representation, and keep calling next() until I get a negative value, and then add that value to the string?
Thanks!
Technically, both are doable, so that’s actually a design question. If you are sure every time you will iterate on that Iterable structure you will need that condition, than go with a condition in the next() method of a subclass of Iterator, but else, you better check in your app outside the Iterator.
Also, the test in the next() method could possibly improve performance, because you will iterate on a fewer number of elements in your applicative code. So if performance is an issue, maybe it’s a good idea.