Guava Tips: Primitives

Guava contains a lot of useful methods and classes to work with primitives and do math with them; in this post we’ll briefly discuss some of them.

Primitive arrays

To help you work with primitives arrays, Guava includes quite a few classes: Longs, Ints, Floats, Doubles, Booleans, and others.

Most of these classes contain variants of the following methods, which work on primitive types and thus avoid any autoboxing issues:

Unsigned support

Java does not support unsigned integers (although some partial support was added in JDK 8). However, Guava contains some utilities to help you. There are two sets of api:

  • the first version is based upon a wrapper, similarly to BigInteger and BigDecimal. The two classes UnsignedInteger and UnsignedLong wrap respectively a 32-bit integer and a 64-bit long in an object, which can do proper unsigned math.
  • if you are willing to sacrifice speed for readability, you can skip the wrappers and use a raw int or long as if it were an unsigned, using the methods of UnsignedInts and UnsignedLongs to work with them. However, this can quite easily lead to subtle mistakes, since there is no compiler errors or warning to help you, so try to isolate as much as possible the use of these classes.

Math

Guava also contains some classes to help you perform mathematics and handle correctly, and portably, overflows, underflows, and other arithmetic errors. There are, again, various classes with all similar methods, notably IntMath, LongMath and DoubleMath, all of which include a lot of methods:

  • factorial, binomial, isPrime, gcd and similar methods to perform standard math operations;
  • variants of addition, subtraction and so on with checks for overflows: checkedAdd and others;
  • divide, logarithms and square roots with an explicit rounding mode;
  • various versions of rounding for doubles.