Java equals()排序 [英] Java equals() ordering
本文介绍了Java equals()排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我尝试对Java中的空字符串执行 .equals()
,则会引发空指针异常.我想知道,如果我想比较一个字符串是否等于某个常量字符串,我可以执行以下操作:
If I try to do a .equals()
on a null string in java, a null pointer exception will be thrown. I am wondering, if I am trying to compare if a string is equal to some constant string, can I do the following:
MY_CONSTANT_STRING.equals(aStringVariable)
我知道它会起作用,但这真的是不好的代码吗?
I know it will work, but is this just really poor code?
推荐答案
This is a standard Java idiom jokingly called a Yoda condition.
我个人更喜欢显式处理null情况,但是Yoda方法已被广泛使用,任何有经验的Java程序员都应该能够立即了解发生了什么.很好用.
Personally I prefer to handle the null case explicitly, but the Yoda way is used a lot and any experienced Java programmer should be able to understand what is going on immediately. It's fine to use.
这篇关于Java equals()排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文