Null pointer exception This pit-daddy anomaly is the most common pit for beginner developers, so today we share a new JDK toolkit for java.util.Objects. There are a lot of tools that can help us avoid null pointer anomalies so that our code is more elegant to write. Let's take a look at what tools this toolkit has.
The famous equals.
Usually we write two strings in comparison with each other.
Object.Equals ("sample");
The biggest problem with this notation is that if the object is null then this is bound to report a null pointer exception. Usually the old driver tells us it's better to write like this.
"Sample", Equals (Object)
It's good to write like this, but if the two objects in the comparison are not known, then we still need to judge the non-null and then use equals. This looks neither elegant nor more code-writing.
JDK1.7 has prepared a toolkit for us to solve this problem.
Java.util.Objects
Objects.equals (Arg1, arg2)
If all two parameters are NULL returns TRUE, if only one is null returns FALSE, other cases call Arg1.equals (ARG2)
Java
CompareTo (Arg1, arg2)
JDK7 's new toy java.util.Objects