Java – why mystring equals(“aString”); Different from “astring” equals(myString);?

I have heard many times that Boolean equals (object o) is used to compare strings. It is best to put the constant on the left side of the function, as shown below:

> Bad:myString. equals(“aString”); > OK: "astring" equals(myString);

Why?

Solution

Because if mystring is null, an exception will occur You know that "astring" will never be null, so you can avoid this problem

Usually you will see libraries that use nullsafeequals (mystring, "astring"); It's everywhere to avoid this (because most of the time you compare objects, they're not generated by the compiler!)

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
分享
二维码
< <上一篇
下一篇>>