Sometimes you need to write a method that takes an argument indicating how many times a certain thing should be done with the option of doing it an unlimited number of times. A straightforward writing might look like this:
/** Pass in -1 to work forever. */
public void doStuff(int iterations) {
int count = 0;
while (count < iterations || iterations == -1) {
foo();
count++;
}
}
If that just bugs you because one of the conditions will always be unnecessary to check--it bugs me--then what about this?
/** Pass in -1 to work forever. */
public void doStuff(int iterations) {
final long maxCount = iterations == -1 ? Long.MAX_VALUE : iterations;
int count = 0;
while (count++ < maxCount) {
foo();
}
}
Since an int can never be as much as Long.MAX_VALUE, you've got your infinite iterations, and there's only the one condition to check. All it requires is that you know
how big the primitive types are in java and understand
how two's complement numbers work.
No comments:
Post a Comment