1

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
  • if with break in a while(true) loop ? Commented Jul 21, 2009 at 16:54
  • 3
    Another way to go is to TRY IT. You have javac and you can try all kinds of stuff out. Then your question might either get answered, or you might say, "I'm getting this result... why?" Good luck. Commented Jul 21, 2009 at 17:01
  • 1
    Also note, while we're here: in Java, you should name your variable instances with lowercase names. So Enumeration parameterEnum... Commented Jul 21, 2009 at 17:03

4 Answers 4

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I figured it was a trick question. I'm feeling suspicious today.
I'm still pretty suspicious. I think that was a homework question.
2

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.

Comments

1

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 ;-)

2 Comments

I've never seen someone so excited about big-O.
and you haven't seen me watching pr0n!! xD
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.