Some people (in-house people) still write the following code when comparing objects. To avoid NullPointerException, try writing constants first,
if ("hoge".equals(hoge)) {
//Never get a NullPointerException
}
I do null check first and then compare.
if (hoge != null && hoge.equals("hoge")) {
//If hoge is NULL, the following String.equals is not executed
}
If you are using Java 7 or later, please use `java.util.Objects.equals (Object a, Object b)`
.
In this case, it makes a comparison considering null.
if (Objects.equals(hoge, "hoge")) {
//processing
}
Even if the pointer (address in memory) of the object is different Rest assured that the stored values will be compared with each other.
String hoge1 = "hoge";
String hoge2 = new String("hoge");
System.out.println(hoge1 == hoge2); // false
System.out.println(hoge1.equals(hoge2)); // true
System.out.println(Objects.equals(hoge1, hoge2)); // true
In writing this article, I revisited java.util.Objects. I didn't know this! I will write something like that.
toString
Method to convert to String type. If the conversion target is null, it will be converted to the character string null.
Object obj = null;
String str = Objects.toString(obj);
System.out.println(Objects.equals(str, "null")); // true
System.out.println(Objects.equals(str, null)); // false
It's very nice to be able to avoid nulls, but I think there are some situations where it's difficult to convert to the string null. In such a case, you can change the value returned when null by setting a character string in the second argument.
Object obj = null;
String str = Objects.toString(obj, "It's NULL!");
System.out.println(str); //Output result: NULL!
I knew the toString method, but I didn't know that I could set the second argument.
isNull/nonNull
isNull is a method that returns true if the argument is NULL. nonNull is a method that returns false if the argument is NULL.
Object obj = null;
System.out.println(Objects.isNull(obj)); // true
System.out.println(Objects.nonNull(obj)); // false
obj == null
Looks more stylish.
(I didn't see the difference in behavior between obj == null
and obj! = null
...)
requireNonNull
A method to check if the target is NULL. If it is NULL, a NullPointerException will occur.
Object obj2 = Objects.requireNonNull(obj1);
If you try to do a null check without using this method
if (obj1 == null) {
throw new NullPointerException();
} else {
Object obj2 = Objects.requireNonNull(obj1);
}
Will be. I think it's a simple and convenient method.
Objects (Java Platform SE 7) The old way of writing is old! ?? java.util.Objects is too convenient
Recommended Posts