Java.lang.Object VS java.util.Objects, what's the difference?

As we all know, Object is the root class in Java. I found a class called Objects that looks very similar to Object .

The theis Objects class confused me a bit. Can someone tell me when and where should we use the Objects class?

+4
source share
2 answers

Objects simply contains a set of useful methods, useful in combination with instances of Object . Note that it cannot be created (it is final and does not have a public constructor) and contains only static methods.

The naming scheme for using utility methods in classes with a pluralized name is quite common in the JDK:

  • Collections
  • Arrays (although, strictly speaking, there is no corresponding Array class)
  • ...

Other libraries also use this scheme, for example Guava :

+15
source

One typical use of the Objects class:

 public void foo(SomeClass bar) { Objects.requireNonNull(bar, "custom msg"); // // Ensure an object is not null. } 

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"); } 
0
source

All Articles