tags:

views:

190

answers:

4

I have a code something like this

Enumeration parameterEnum = request.getParameterNames()
while(parameterEnum.hasMoreElements()){}

what is the difference if I change it from a while statement into an if statement?

+3  A: 

If you change it to an if it will either execute once or not at all - a while statement will execute indefinitely until ParameterEnum.hasMoreElements() returns false.

Andrew Hare
i think that is what I'm looking for. thanks!
I figured it was a trick question. I'm feeling suspicious today.
skaffman
I'm still pretty suspicious. I think that was a homework question.
CaptainAwesomePants
+1  A: 

The if will be much, much faster!!! its complexity is O(1) and that of while's is O(N)!!!

So, the larger the input is, the better it is to use an if instead of a while ;-)

fortran
Where's the button to up and downvote at the same time?
Georg
I dunno xD but vote up just in case :-p
fortran
I've never seen someone so excited about big-`O`.
pianoman
and you haven't seen me watching pr0n!! xD
fortran
+2  A: 

If I understand what you are asking, the current code would keep running whatever is in the brackets until there are not elements. This assumes that what is in the brackets takes off elements. As literally shown above, it is an infinite loop and will never end.

If you convert the while to an if, then what is in the brackets will run only once.

If Request.getParameterNames() returns an "empty" whatever-it-is, then neither case will do anything.

Chris Arguin
A: 

You might be thinking of a for statement, not an if.

if(ParameterEnum.hasMoreElements()) {}

The if will only run once

while(ParameterEnum.hasMoreElements()) {}

the while will run continuously, unless you increment the enum.

the other option is for:

for(Enumeration paramEnum = Request.getParameterNames(); 
                              parameEnum.hasMoreElements();) {}

this is similar to the while, and will run for as long as the hasMoreElements() method returns true, so incrementing the enum with nextElement() is important.

akf