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