Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reason for Objects static methods in Java 7

Tags:

java

java-7

It seems that with Java 7, Objects class is providing a lot of functionality already covered in other parts of the language.

Take toString() for example. The following will produce the same results:

Objects.toString(12);
String.valueOf(12);

In fact, Objects.toString is defined as:

public static String toString(Object o) {
    return String.valueOf(o);
}

Say we're dealing with actual classes. Is one preferred over another?

Objects.toString(o);
o.toString(); 

What are language designers telling us here? Should we start preferring Objects's solution instead of what's already available? What is a long term rationale for something like this?

like image 262
James Raitsev Avatar asked Dec 26 '22 21:12

James Raitsev


1 Answers

See the documentation for said class:

This 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.

So it's mostly to save you from an additional null guard.

like image 125
Joey Avatar answered Jan 05 '23 09:01

Joey