When to use ‘Java util. Objects.*’?
•
Java
I'm browsing the seven functions of Java. They talked about Java util. Objects course
What I can't understand is the functional difference between them
java.util.Objects.toString(foo) vs foo == null ? "":foo.toString()
What I can only see is an empty check and functional notation instead of OOP style
What did I miss?
Solution
java. util. Objects. The main advantage of toString () is that you can easily use it for potentially null return values instead of creating new local variables (or worse, calling the function twice)
comparison
Foo f = getFoo(); String foo = (f==null) ? "null" : f.toString();
Or a daunting and seductive mistake
String foo = (getFoo()==null) ? "null" : getFoo().toString()
To objects based Version of toString
String foo = Objects.toString(getFoo());
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码