String.equals() argument ordering

后端 未结 10 1521
太阳男子
太阳男子 2020-11-27 06:56

I recently received a downvote for using the following in a recent answer:

String word = ...;
if (\"s\".equals(word) || \"y\".equals(word)

10条回答
  •  情书的邮戳
    2020-11-27 07:10

    You can write

    if (word != null && (word.equals("s") || word.equals("y")))
    

    instead of

    if ("s".equals(word) || "y".equals(word))
    

    In this case, first one will never cause any NullpointerException, but in my point of view in this case the 2nd one is better, though it is in Yoda Condition

提交回复
热议问题