简体   繁体   中英

Java: Impact of using 'if' instead of while loop during an iteration

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它要么执行一次或者根本没有-一个while声明将无限期执行,直到ParameterEnum.hasMoreElements()返回false。

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.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM