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.
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 new
Listbacked by the given array, thus avoiding the boxing of the primitives until some methods which require it are called on the given
hashcode(long a), which returns a suitable hash code for the given primitive. Fun fact: the hash code implemented for
x. If you think about it, this is the best hash function you can invent: it’s uniformly distributed and injective!
tryParse(String string), which is similar to the standard JDK method
parseLong, but rather than returning an exception it will return
null, which makes it nicer to use in some cases;
- various methods to work with arrays, such as
contains(long array, long target),
indexOf(long array, long target), all of which do what you would expect them to.
- the first version is based upon a wrapper, similarly to BigInteger and BigDecimal. The two classes
UnsignedLongwrap 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
longas if it were an unsigned, using the methods of
UnsignedLongsto 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.
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
DoubleMath, all of which include a lot of methods: