Java 7 : The new java.util.Objects class

Java Logo

In Java 7, we’ll see a new class : java.util.Objects. This class contains 9 static methods to work on Objects. I found these methods really useful.

First, two really simple methods to assert non-null objects in getter/setter (or other methods, of course) :

  • <T> T nonNull(T obj) : If obj is not null, return obj else throw a NullPointerException.
  • <T> T nonNull(T obj, String message) : If obj is not null return obj else throw a customized NullPointerException with the given message

Some simple examples :

public void setFoo(Foo foo){
    this.foo = Objects.nonNull(foo);
}
 
public void setBar(Bar bar){
    this.foo = Objects.nonNull(bar, "bar cannot be null");
}

Although simple, these methods can improve the readability of code and avoid having to write the is-null check ourselves.

Then, we have two methods to compute a toString() value for Object supporting null objects :

  • String toString(Object o) : Return the toString() value of a non-null object otherwise “null”.
  • String toString(Object o, String nullDefault) : Return the toString() value of a non-null object otherwise return nullDefault

Again, this is useful for code readibility :

public class Bar {
    private Foo foo;
    private Bar parent;
 
    @Override
    public String toString(){
        return "Bar {foo = " + Objects.toString(foo) + ", parent = " + Objects.toString(parent, "no parent, orphan") + "}";
    }
}

I think, it’s a lot better than :

public class Bar {
    private Foo foo;
    private Bar parent;
 
    @Override
    public String toString(){
        return "Bar {foo = " + (foo == null ? "null" : foo.toString()) + ", parent = " + (parent == null ? "o parent, orphan" : parent.toString()) + "}";
    }
}

Isn’t it ?

After that, we also two similar methods for hashing :

  • int hash(Object… values) : Compute a hash code for all the given values
  • int hashCode(Object o) : If 0 is null return 0 othewise return o.hashCode()

If we take again the exemple of the Bar class. If we have to write the hashCode() method without Objects, we could do that :

public class Bar {
    private Foo foo;
    private Bar parent;
 
    @Override
    public int hashCode(){
        int result = 17;
 
        result = 31 * result + (foo == null ? 0 : foo.hashCode());
        result = 31 * result + (parent == null ? 0 : parent.hashCode());
 
        return result;
    }
}

With Java 7, we only have to do that :

public class Bar {
    private Foo foo;
    private Bar parent;
 
    @Override
    public int hashCode(){
        return Objects.hash(foo, parent);
    }
}

And that’s it :)

On the same model, we’ve also two methods for equality checks :

  • boolean equals(Object a, Object b) : Return true if the two arguments are null or they are both not null and a.equals(b) return true, otherwise false.
  • boolean deepEquals(Object a, Object b) : Almost the same as the first method except that if both a and b are arrays, the equality is evaluated using Arrays.deepEquals method.

Once again, that can really ease the coding of equals() methods :

public class Bar {
    private Foo foo;
    private Bar parent;
 
    @Override
    public boolean equals(Object obj){
        if (obj == this) {
            return true;
        } 
 
        if (obj instanceof Bar) {
            Bar other = (Bar) obj; 
 
            if (foo != other.foo) {
                if (foo == null || !foo.equals(other.foo)) {
                    return false;
                }
            } 
 
            if (parent != other.parent) {
                if (parent == null || !parent.equals(other.parent)) {
                    return false;
                }
            } 
 
            return true;
        } 
 
        return false;
    }
}

become :

public class Bar {
    private Foo foo;
    private Bar parent;
 
    @Override
    public boolean equals(Object obj){
        if (obj == this) {
            return true;
        } 
 
        if (obj instanceof Bar) {
            Bar other = (Bar) obj; 
 
            return Objects.equals(foo, other.foo) &amp;&amp; Objects.equals(parent, other.parent);
        } 
 
        return false;
    }
}

Better, no ?

And the last one : <T> int compare(T a, T b, Comparator<? super T> c). This method returns 0 if a == b or if both are null otherwise c.compare(a, b). The support of null is delegated to the comparator.

We’ve covered all the features offered by this new class.

Of course, there is already some methods like that in librairies like Jarkarta Commons or Google Guava, but it’s always better when we doesn’t have to include a library for that kind of features.

I hope you found this post interesting.

Related posts:

  1. Manage focus with Swing in Java
  2. Mock objects with EasyMock
  3. Java Concurrency – Part 3 : Synchronization with intrinsic locks
  4. The reserved keywords of the Java Language
  5. JR Virtual machines
  • http://www.joshuatessier.com/ Joshua Tessier

    My favorite out of all of those is the Objects.hash method. That’s wicked.

    • Terr

      One of the things I like about Netbeans is that you can have it code-generate that kind (the “old way”) of hashCode() and equals() methods: You just tick off which properties it needs to generate them for.

  • http://www.joshuatessier.com/ Joshua Tessier

    My favorite out of all of those is the Objects.hash method. That’s wicked.

    • Terr

      One of the things I like about Netbeans is that you can have it code-generate that kind (the “old way”) of hashCode() and equals() methods: You just tick off which properties it needs to generate them for.

  • http://www.introspectrum.com Website Performance

    No one has needed to use code like ‘foo == null ? “null” : foo.toString()’ for a long time now.

    ‘String.valueOf()’ already exists to handle null-safe conversion of objects to strings, using the same ‘null’ default value.

    For more information see:

    http://java.sun.com/javase/6/docs/api/java/lang/String.html#valueOf(java.lang.Object)

  • http://www.introspectrum.com Website Performance

    No one has needed to use code like ‘foo == null ? “null” : foo.toString()’ for a long time now.

    ‘String.valueOf()’ already exists to handle null-safe conversion of objects to strings, using the same ‘null’ default value.

    For more information see:

    http://java.sun.com/javase/6/docs/api/java/lang/String.html#valueOf(java.lang.Object)

  • http://www.teamten.com/lawrence/ Lawrence Kesteloot

    Thanks for writing this up. How is Object.toString(Object) different from String.valueOf(Object)? I’m guessing the only advantage is that Object.toString() is sitting right next to the version with the default value.

  • http://www.teamten.com/lawrence/ Lawrence Kesteloot

    Thanks for writing this up. How is Object.toString(Object) different from String.valueOf(Object)? I’m guessing the only advantage is that Object.toString() is sitting right next to the version with the default value.

  • http://hypergraphs.de/ Axel Rauschmayer

    Note: String-+ already does what Objects.toString(Object) offers, thus you don’t need to write Objects.toString(foo) in the example above, just foo is enough. Objects.toString(o) is equivalent to “”+o.

  • http://hypergraphs.de/ Axel Rauschmayer

    Note: String-+ already does what Objects.toString(Object) offers, thus you don’t need to write Objects.toString(foo) in the example above, just foo is enough. Objects.toString(o) is equivalent to “”+o.

  • Leon Breedt

    Sounds like you need C# extension methods in Java :)

    I have extension methods for dealing with exactly these cases, the difference being that in my source code I can call the extension method on the variable itself, and the compiler goes and re-writes it to the equivalent of “Objects.hashCode()”.

    E.g.

    public static class ObjectExtensions
    {
    public static int SafeHashCode(this object o)
    {
    return o != null ? o.GetHashCode() : 0;
    }
    }

    And then use it like this:

    object o = null;
    int i = o.SafeHashCode(); // Never throws null reference exception.

  • Leon Breedt

    Sounds like you need C# extension methods in Java :)

    I have extension methods for dealing with exactly these cases, the difference being that in my source code I can call the extension method on the variable itself, and the compiler goes and re-writes it to the equivalent of “Objects.hashCode()”.

    E.g.

    public static class ObjectExtensions
    {
    public static int SafeHashCode(this object o)
    {
    return o != null ? o.GetHashCode() : 0;
    }
    }

    And then use it like this:

    object o = null;
    int i = o.SafeHashCode(); // Never throws null reference exception.

  • Ben Smith-Mannschott

    Object.toString(o) duplicates String.valueOf(o). This raises the question of where a static method like this more properly belongs: in the String class (what it produces), in the Object class (what it consumes), or in a utility class like Objects. (IMHO Objects looks like a good place for it.)

    This looks like a good collection of methods: I’ve even written nonNull myself on a few occasions.

    hash(…) looks nice too. The result is easier to read than the usual solution: letting the IDE generate a bletcherous-looking, but correct, implementation of hashCode() for you. I’ve almost written hash(…) myself a few times as well, but I stopped because I worried about the efficiency of boxing a bunch of primitives up every time hashCode() gets called.

  • Ben Smith-Mannschott

    Object.toString(o) duplicates String.valueOf(o). This raises the question of where a static method like this more properly belongs: in the String class (what it produces), in the Object class (what it consumes), or in a utility class like Objects. (IMHO Objects looks like a good place for it.)

    This looks like a good collection of methods: I’ve even written nonNull myself on a few occasions.

    hash(…) looks nice too. The result is easier to read than the usual solution: letting the IDE generate a bletcherous-looking, but correct, implementation of hashCode() for you. I’ve almost written hash(…) myself a few times as well, but I stopped because I worried about the efficiency of boxing a bunch of primitives up every time hashCode() gets called.

  • Anton Murauyou

    Sorry, but nothing useful actually of this methods I find.

    First two are an essential assert (those who didn’t use it earlier – read Java 5 Docs).

    Null is always printed in String as soon as you append it simply to String: “”+o as Axel Rauschmayer said.
    The second one with nullDefault even more messes the code – it becomes hard to understand and soon we’ll come to extension methods like in C# – but to tell the truth that is what a REAL burden in code (I don’t know what’s .Net programmers are proud of…)

    In almost all IDEs now ‘equals’ and ‘hashCode’ are autogenerated.

    And finally – I will miss Comparable interface. I don’t want all my objects to be comparable?! Why should I?

    • Maxim Sultakov

      The purpose of the Objects.notNull() method is absolutely different from the purpose of the ‘assert’ keyword. There are several good articles on this topic and you can easily find them.

  • Anton Murauyou

    Sorry, but nothing useful actually of this methods I find.

    First two are an essential assert (those who didn’t use it earlier – read Java 5 Docs).

    Null is always printed in String as soon as you append it simply to String: “”+o as Axel Rauschmayer said.
    The second one with nullDefault even more messes the code – it becomes hard to understand and soon we’ll come to extension methods like in C# – but to tell the truth that is what a REAL burden in code (I don’t know what’s .Net programmers are proud of…)

    In almost all IDEs now ‘equals’ and ‘hashCode’ are autogenerated.

    And finally – I will miss Comparable interface. I don’t want all my objects to be comparable?! Why should I?

    • Maxim Sultakov

      The purpose of the Objects.notNull() method is absolutely different from the purpose of the ‘assert’ keyword. There are several good articles on this topic and you can easily find them.

  • Roridge

    Finally, I have been writing nonNull utility methods for years in various companies!

    Anyone who doesn’t find these useful isn’t coding their API defensively and has to answer to Josh Bloch.

  • Roridge

    Finally, I have been writing nonNull utility methods for years in various companies!

    Anyone who doesn’t find these useful isn’t coding their API defensively and has to answer to Josh Bloch.

  • Geoffrey De Smet

    I was hoping it would standarize much of the Apache commons-lang’s ObjectUtils and StringUtils class methods.
    The methods hash and equals look usefull, other’s don’t.
    Especially the compare method looks useless. A compare variant based on Comparable instances (without the need to supply a Comparator), could be usefull.

    Like they say: “Good programmers appreciate the features you put in, great programmers appreciate the features your leave out.”

  • Geoffrey De Smet

    I was hoping it would standarize much of the Apache commons-lang’s ObjectUtils and StringUtils class methods.
    The methods hash and equals look usefull, other’s don’t.
    Especially the compare method looks useless. A compare variant based on Comparable instances (without the need to supply a Comparator), could be usefull.

    Like they say: “Good programmers appreciate the features you put in, great programmers appreciate the features your leave out.”

  • Baptiste Wicht

    Effectively, i forgot the String.valueOf() method, with the same purpose. But i think it’s a good think to have a centralized set of methods for objects.

    I completely agree with the auto generation of the equals and hashcode methods with the IDEs. But that makes not the code clearer and if we have a bug in one of this methods, that could be difficult to find.

  • Baptiste Wicht

    Effectively, i forgot the String.valueOf() method, with the same purpose. But i think it’s a good think to have a centralized set of methods for objects.

    I completely agree with the auto generation of the equals and hashcode methods with the IDEs. But that makes not the code clearer and if we have a bug in one of this methods, that could be difficult to find.

  • http://blog.peterbecker.de Peter Becker

    I tend to side with SQL on the “(null == null)?” question: the answer should always be “false”. The semantics of null are not clear, so assuming two null values are identical is most likely not a good idea. For example: if two different hash lookups fail and thus two values are null, should that mean the two values are identical?

    Note that Java already has similar behavior with the NaN, e.g. (Double.NaN == Double.NaN) is false. Again the reasoning is that the results of two failed operations should not be comparable.

    Based on this reasoning I don’t like the compare method either. And even if you want to do it, a better option would be to create a NullSafeComparator that delegates anything non-null to another. If that comes with a static factory method you could just do:

    Set mySet = new TreeSet( NullSafeComparator.createFrom(someNonNullSafeComparatorOnDouble));

    But as I said: two nulls should not be considered equal unless proven otherwise.

  • http://blog.peterbecker.de Peter Becker

    I tend to side with SQL on the “(null == null)?” question: the answer should always be “false”. The semantics of null are not clear, so assuming two null values are identical is most likely not a good idea. For example: if two different hash lookups fail and thus two values are null, should that mean the two values are identical?

    Note that Java already has similar behavior with the NaN, e.g. (Double.NaN == Double.NaN) is false. Again the reasoning is that the results of two failed operations should not be comparable.

    Based on this reasoning I don’t like the compare method either. And even if you want to do it, a better option would be to create a NullSafeComparator that delegates anything non-null to another. If that comes with a static factory method you could just do:

    Set mySet = new TreeSet( NullSafeComparator.createFrom(someNonNullSafeComparatorOnDouble));

    But as I said: two nulls should not be considered equal unless proven otherwise.

  • Pingback: Links « Beautiful Discovery

  • Pingback: Pedro Newsletter 01-05.04.2010 « Pragmatic Programmer Issues – pietrowski.info

  • Pingback: New Features in Java 7 (Dolphin) « Kata learns to code