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 Link to heading
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:
List<Long> asList(longs... backingArray)
, which returns a newList
backed by the given array, thus avoiding the boxing of the primitives until some methods which require it are called on the givenList
;hashcode(long a)
, which returns a suitable hash code for the given primitive. Fun fact: the hash code implemented forint x
is…x
. If you think about it, this is the best hash function you can invent: it’s uniformly distributed and injective!max(long... array)
andmin(long... array)
;tryParse(String string)
, which is similar to the standard JDK methodparseLong
, but rather than returning an exception it will returnnull
, which makes it nicer to use in some cases;- various methods to work with arrays, such as
concat(long[]... arrays)
,contains(long[] array, long target)
,indexOf(long[] array, long target)
, all of which do what you would expect them to.
Unsigned support Link to heading
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
andUnsignedLong
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
orlong
as if it were an unsigned, using the methods ofUnsignedInts
andUnsignedLongs
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 Link to heading
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: