Java:API:Objects

From Juneday education
Jump to: navigation, search

Description

This java.util.Objects class consists of static utility methods for operating on objects. These utilities include null-safe or null-tolerant methods for computing the hash code of an object, returning a string for an object, and comparing two objects. It was added to the Java API in Java 7.

Some useful methods

requireNonNull(T obj)

public static <T> T requireNonNull(T obj)

public static <T> T requireNonNull(T obj,
                                   String message)

This utility method can be used to generate a NullPointerException if the argument is null. Let's for instance say that you are writing a constructor for a class, Student. The constructor takes two arguments, String name and String email. Your class invariant is that all Student objects have a name and can't have null as the value for the name instance variable.

Instead of writing an if statement, you can call the requireNonNull() method. The method returns the argument if it is not null, and throws a null pointer exception otherwise:

import java.util.Objects;

public class Student {

  private String name; // required
  private String email; // optional

  public Student(String name, String email) {
    this.name = Objects.requireNonNull(name, "Name cannot be null"); // will throw exception if null
    this.email = email; // can be null
  }
  ...
  ...
}

toString(Object o, String nullDefault)

public static String toString(Object o, String nullDefault)

This method returns toString() on the first argument if it is not null, otherwise it returns the second argument.

Let's continue with our Student class. We are writing the toString() method of our Student class and want to return a String consisting of the Student's name followed by the email if the email is not null. If the Student doesn't have an email, we want to return only the name. Instead of using if statements or the ternary operator, we can use this method:

  @Override
  public String toString() {
    String result = name + " " + Objects.toString(email, "");
    return result.trim();
  }

boolean nonNull(Object obj)

public static boolean nonNull(Object obj)

This method is meant to be used as a lambda (method reference) when filtering a functional stream. Let's say we are processing a stream of a list of references where some references are null. We can't apply method calls on each element in the stream, because we would get a null pointer exception on the first null reference. So we can filter the stream, using Objects::nonNull:

System.out.println(emails);
// [null, a@email.com, null, B@EMAIL.COM, C@email.COM, null, D@emaIL.COM]
// We want to
// 1. ignore null references
// 2. apply toLowerCase on each email
// 3. print them:
emails.stream()
  .filter(java.util.Objects::nonNull)
  .map(s -> s.toLowerCase())
  .forEach(System.out::println);
/*
a@email.com
b@email.com
c@email.com
d@email.com
*/