Java Programming Tutorials

Java programming tutorials with many code examples!

Java Objects equals hashcode


How to implement equals and hashcode using java.util.Objects? In the following example we show how to use these great, null-insensitive helper methods.


Java 7 came with long time awaited utility class java.util.Objects. It contains static helper methods for working with objects. Here we show how to use equals and hash methods that are null-insensitive and ease implementation of equals and hashcode:


import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Objects;

public class ObjectsEqualsHashcode {

    public static class Player {
        public final String login;

        public Player(String login) {
            this.login = login;

        public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;
            Player player = (Player) o;
            // accepts nulls:
            return Objects.equals(login, player.login);

        public int hashCode() {
            // varargs and accepts nulls:
            return Objects.hash(login);

        public String toString() {
            return "Player{login='" + login + "'}";

    public static void main(String[] args) {
        Collection<Player> players = Arrays.asList(
                new Player(null),
                new Player("player1"),
                new Player("player2"));
        System.out.println("Players: " + players);

        Collection<Player> sortedPlayers = new HashSet<>(players);
        System.out.println("In Set: " + sortedPlayers);

        // will not throw NullPointerException:
        sortedPlayers.contains(new Player(null));

The code is straightforward. There are two important things:

  1. Objects.equals() and Objects.hash() accepts null.
  2. Objects.hash() accepts many objects.

And here’s the output of running the code:

Players: [Player{login='null'}, Player{login='player1'}, Player{login='player2'}]
In Set: [Player{login='player2'}, Player{login='player1'}, Player{login='null'}]
Was it helpful? Share!