The Student Room Group
Reply 1
Are these the methods of Iterator?

hasNext() tells you if there are any more elements.
next() iterates to the next element and returns it.

When you use an iterator to loop though a collection it is usually like this:


while(iter.hasNext())
{
Sausage s = (Sausage)iter.next()
}


This is what it would be like if you were iterating through a collection of Sausage objects. If the iterator uses generics you use generics you wouldn't need to cast.
I presume you mean of the Iterator class? Again if you ask questions about methods say which class they are of as we can only guess what your after. Like I also said last I answered this type of question for you, the answers are in the API. You should keep it bookmarked.

hasNext() - "Returns true if the iteration has more elements"
So you can check if there are more objects you can get from the iterator, and if there are it returns true. If there are no more objects it will return false.

next() - "Returns the next element in the iteration"
So if there is a next item, it will be returned. If there isn't it'll throw a 'NoSuchElementException', but if you use iterators properly you should never encounter it.

Essentially you check if there is a variable a next variable with hasNext(), and if so, you get it with next(). Otherwise how else will you know if you are at the end of the list of objects? The two methods are usually used together where instead of using a for loop you can use a while loop, like so:

Iterator<Object> iterator = list.iterator();
Object myObject;
while (iterator.hasNext()) {
myObject = iterator.next();
// do something with myObject
}


In the while loop above I am first checking if the iterator has a next element, and if it does I then store it into a variable and work with it in the while loop. Personally I always prefer for/each loops as it's less code and more straightforward to read. I suspect iterators were a solution to get the functionality of for/each before Java 5. If you don't know them already, I'd recommend researching them next. But you still need to know about iterators.
You can also use hasNext to test for input ends. Use it in a while loop to scan through user input.
This is sort of "off topic" but is there an Iterator class already built into java? Or do you have to create your own and implement it?
Reply 5
samicemalone
This is sort of "off topic" but is there an Iterator class already built into java? Or do you have to create your own and implement it?


Iterator is already part of the Java library. It's part of the collections framework.
Though it's an interface, not a class, so if you want to iterate over a custom collection, you'll need to implement it yourself.

Latest

Trending

Trending