Objects Utility Class in Java
Many everyday object chores have a trap for null: a.equals(b) throws if a is null, obj.hashCode() throws, and a constructor that quietly stores a null causes a crash much later, far from the real mistake. java.util.Objects (with an s, not the Object class) is a small utility class of static methods that handle these chores null-safely in one line.
The Most Useful Methods
import java.util.Objects;
public class Helpers {
static final class Member {
private final String name;
private final String city;
Member(String name, String city) {
this.name = Objects.requireNonNull(name, "name must not be null");
this.city = city;
}
@Override
public boolean equals(Object o) {
return o instanceof Member m
&& Objects.equals(name, m.name)
&& Objects.equals(city, m.city);
}
@Override
public int hashCode() { return Objects.hash(name, city); }
@Override
public String toString() {
return name + " from " + Objects.toString(city, "unknown city");
}
}
public static void main(String[] args) {
Member a = new Member("Srihitha", null);
Member b = new Member("Srihitha", null);
System.out.println(a);
System.out.println(a.equals(b) + " " + (a.hashCode() == b.hashCode()));
System.out.println(Objects.requireNonNullElse(null, "guest"));
System.out.println(Objects.isNull(null) + " " + Objects.nonNull(a));
try {
new Member(null, "Hyderabad");
} catch (NullPointerException e) {
System.out.println("Rejected: " + e.getMessage());
}
try {
Objects.checkIndex(5, 3);
} catch (IndexOutOfBoundsException e) {
System.out.println(e.getMessage());
}
}
}Srihitha from unknown city
true true
guest
true true
Rejected: name must not be null
Index 5 out of bounds for length 3How it works
Objects.requireNonNull(name, message)returnsnameif it isn't null, and throwsNullPointerExceptionwith your message if it is. The constructor fails immediately, at the real mistake.Objects.equals(x, y)istrueif both are null,falseif only one is, and otherwise callsx.equals(y). Herecityis null in both members, and nothing throws.Objects.hash(fields...)builds a hash code from several fields, null-safely.Objects.toString(obj, fallback)gives the fallback text for null.requireNonNullElse(value, default)returns a default for null.checkIndex(index, length)throws the standard bounds message for a bad index.
Quick Reference
| Method | Returns |
|---|---|
equals(a, b) | true if both null or a.equals(b) |
hash(values...) | Combined hash code of the values |
hashCode(o) | o.hashCode(), or 0 for null |
toString(o) / toString(o, fallback) | "null" or the fallback for null |
requireNonNull(o) / requireNonNull(o, message) | o, or throws NullPointerException |
requireNonNullElse(o, default) | o, or the default if null |
requireNonNullElseGet(o, supplier) | o, or computes a default |
isNull(o) / nonNull(o) | Boolean checks, handy in streams (covered later in the course) |
checkIndex(i, length) | i, or throws IndexOutOfBoundsException |
compare(a, b, comparator) | 0 if a == b, otherwise the comparator's result |
Common Mistakes
Confusing Object and Objects. Object is the root class; Objects is a utility class in java.util.
Calling requireNonNull without using its result. It returns the value, so assign it in one line: this.name = Objects.requireNonNull(name).
Using Objects.hash on a hot path with many calls. It creates an array each time; for very frequently hashed objects, compute and cache the hash yourself.
Practice
- Easy: Write a
Bookclass whose constructor rejects a null title withrequireNonNulland a clear message. - Harder: Write
equalsandhashCodefor aContactwithname,phoneand an optionalemailthat may be null, usingObjects.equalsandObjects.hash.
Key Takeaways
Was this tutorial helpful?