Andreas Hartmann Andreas Hartmann - 1 year ago 74
Java Question

How to 'pre increment' a BigInteger in Java?

I have a

loop with
s, something like this:

for(BigInteger a = BigInteger.valueOf(1); a.compareTo(someBigInteger); ++a) {...

Obviously I can't use the
operator on a non-primitive. How do I work around this?

Also, I have to use
in this scenario.

Answer Source

++a is a prefix increment, not a postfix increment, but in the context of a for-loop it doesn't really matter, as you ignore the return value of that statement anyway. In any event, this functionality could be acheieved by calling BigInteger.add. Also note that compareTo returns an int, and since Java does not have implicit casts between ints and booleans (like, e.g., C does), you'd have to compare it's result to 0 to see if a is smaller, larger or equal to someBigInteger):

for (BigInteger a = BigInteger.ONE; 
     a.compareTo(someBigInteger) < 0; 
     a = a.add(BigInteger.ONE)) {...