File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Problem with Iterator.hasNext() Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Problem with Iterator.hasNext()" Watch "Problem with Iterator.hasNext()" New topic

Problem with Iterator.hasNext()

Sushma Menon

Joined: Nov 24, 2001
Posts: 1
Is there any difference between "while (iterator.hasNext()) {" and "while (iterator.hasNext() == true)". Logically both the statements seem correct but while exectuting the latter, sometimes I get unexpected results. While when the former statement is used, always I got the expected result.
Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
No the result is the same. The first solution directly evaluates the result of hasNext(), the second solution first compares the result of hasNext() == true and if this comparison is true then you enter the loop.
Joel McNary

Joined: Aug 20, 2001
Posts: 1824

Could you please elaborate on the "unexpected results." I can't think of anything that would cause this, as the statements should be equal, except that the latter places an extra operation on the stack. Once that operation is evaluated, everthing else should be equal, side effects included.

Piscis Babelis est parvus, flavus, et hiridicus, et est probabiliter insolitissima raritas in toto mundo.
Dirk Schreckmann

Joined: Dec 10, 2001
Posts: 7023
Welcome to JavaRanch!
We ain't got many rules 'round these parts, but we do got one. Please change your display name to comply with The JavaRanch Naming Policy. (How's about just replacing that underscore with a space?)
Thanks Pardner! Hope to see you 'round the Ranch!

[How To Ask Good Questions] [JavaRanch FAQ Wiki] [JavaRanch Radio]
I agree. Here's the link:
subject: Problem with Iterator.hasNext()
It's not a secret anymore!