Objects – A Not Very Well Known Utility Class In Java

The Java API has some quite useful classes which are not well known. One of them is the Objects class with several static helper methods. Most of them help dealing with null values (which is quite a pain if you have to do it by yourself). The Objects class is available since Java 7.

I really like the requireNonNull methods as you often have to write code that checks for null values. As it can be seen in the code snippet below, the static method requireNonNull is available in two versions. I prefer the one with the additional message as a NullPointerException is not very expressive in itself.

public void solve(String problem) {
    // throws NullPointerException if problem is null

    // throws NullPointerException with passed text if problem is null
    Objects.requireNonNull(problem,"problem is null");

    // solve problem

Null can also be problematic if you want to create a String as it is automatically transformed to an empty String. This is not always desired as null and an empty String cannot be differentiated anymore. The Objects class provides the toString method, which is also available in two versions as it can be seen in the code listing below.

public void printProblem(String problem) {
     // converts null to "null", otherwise calls toString()
     String output = Objects.toString(problem);

     // converts null to "no problem given", otherwise calls toString()
     String anotherOutput = Objects.toString(problem,"no problem given");

     // print problem

There are also two methods regarding the generation of hashcodes. Using the Objects.hashcode(Object o) method, the hashcode method of the Object o is called. In case of a null reference, 0 is returned. For computing the hash value for several objects, you can resort to Objects.hash(Object… values) which delegates the hash generation to the Arrays.hashCode method. These methods are not that useful to me as almost always I use an IDE to generate the hashCode method of an Object using its fields for me.

Additionally, the methods named equals and deepEquals help to compare objects for equality taking the null value explicitly into account while compare itself uses a Comparator. I can not see any immediate use for me regarding these methods either, but perhaps an occasion for them may arise.

I recommend that you read through the source code of the Objects.class. It is quite simple and easy to understand. You could write a class with the same functionality by yourself, however, you get this behaviour fully tested and already implemented for free! So use it!