One typical use of the Objects class:
public void foo(SomeClass bar) { Objects.requireNonNull(bar, "custom msg");
Output when bar is null:
Exception in thread "main" java.lang.NullPointerException: custom msg at java.util.Objects.requireNonNull(Unknown Source) at com.example.ObjectsUsage.main(ObjectsUsage.java:24)
Another one to build hashCode from fields:
@Override public int hashCode() { return Objects.hash(this.foo, this.bar, this.duh); }
And the most useful:
if (Objects.equals(sun, moon)) { log("I swear I am in earth"); }
source share