As we all know,Object
is the root class in Java. I found a class named Objects
that looks quite similar toObject
.
TheisObjects
class has confused me for a while. Can anybody tell me when and where we should use the Objects
class?
As we all know,Object
is the root class in Java. I found a class named Objects
that looks quite similar toObject
.
TheisObjects
class has confused me for a while. Can anybody tell me when and where we should use the Objects
class?
Objects
simply contains a set of utility methods that are useful in combination with Object
instances. Note that it can't be instantiated (it's final
and it has no public
constructor) and only contains static
methods.
The naming schema of putting utility methods in pluralized-name classes is pretty common in the JDK:
Collections
Arrays
(although strictly speaking there is no corresponding Array
class)Other libraries also use this scheme, for example Guava:
One typical use of 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 construct hashCode from the fields:
@Override public int hashCode() {
return Objects.hash(this.foo, this.bar, this.duh);
}
And the most useful one:
if (Objects.equals(sun, moon)) {
log("I swear I am in earth");
}
Yes, there is lot of difference of both Object and Objects classes
Object Class
Class Object is the root of the class hierarchy. Every class has Object as a superclass and this class is available since JDK1.0
Class Declaration : public class Object
Package : java.lang.Object
Methods : It has only instance methods as clone(), equals(Object obj), hashCode(), notify(), notifyAll(), toString(), wait() etc.
Objects Class
Objects class is final class and it consists of only static utility methods for operating on objects, Using Objects class methods, one can smartly handle NullPointerException as these are null-safe methods for computing the hash code of an object, returning a string for an object, and comparing two objects. This class is available since JDK1.7
Class Declaration : public final class Objects extends Object
Package : java.util.Objects
Methods : It has only static methods as equals(Object a, Object b), hash(Object... values), isNull(Object obj), nonNull(Object obj), toString(Object o), hashCode(Object o) etc.
Note : If you have JDK1.7 then you can only use Objects class