When I somehow investigated how to use equals at work, I found a higher-grade usage, so I will talk about it. I already know this! Please look at it with warm eyes. And please point out any mistakes.
I think the equals method is often used when comparing strings of the String class. At that time, I used to call it like this.
equals.java
str.equals("hoge");
However, with this call method, if str is null, equals will be called from null, so a *** nullPointerException exception *** will occur.
As a way to avoid this exception, it is ant to check for null with an if statement, but you can avoid the exception by changing the equals method a little.
That's here.
equals.java
"hoge".equals(str);
It's easy. It's just the opposite of str and "hoge". This call returns false instead of nullPointerException. Therefore, the *** nullPointerException exception *** will not occur.
This time I introduced the equals method of the String class, but there is also the equals method of the Object class.
equals.java
Objects.equals(str1,str2);
This explanation will be on another occasion.
From now on, when using the equals method, I want to call the string first.
Recommended Posts