Java 这个空字符串检查是多余的吗?
在Android的Java 这个空字符串检查是多余的吗?,java,android,string,Java,Android,String,在Android的frameworks/base/services/core/java/com/Android/server/policy/PhoneWindowManager.java中,有一个条款: //if device type is tablet force enable NavigationBar and forbid NavigationBar move String deviceType = SystemProperties.get("sys.device.typ
frameworks/base/services/core/java/com/Android/server/policy/PhoneWindowManager.java
中,有一个条款:
//if device type is tablet force enable NavigationBar and forbid NavigationBar move
String deviceType = SystemProperties.get("sys.device.type");
if (! "".equals(deviceType) && deviceType.equals("tablet")) {
mNavigationBarCanMove = false;
mHasNavigationBar = true;
}
是
!“.equals(deviceType)&&&
完全冗余,或者它有什么意义吗?是的,在这种情况下它是冗余的,因为第二个子句涉及第一个子句(如果deviceType
不为空),因此可以简化执行以下操作:
//Use constant string to perform comparison to avoid possible NPE
if("tablet".equals(deviceType)) {}
如果(!“”.equals(deviceType)和&deviceType.equals(“tablet”),语句不好,原因如下:
“”.equals(deviceType)
在此实例中是无值的
deviceType.equals(“tablet”)
是比较字符串变量和常量的一种粗心方法
使用代码>可能会让软java程序员感到困惑(其精确度更高:!或&?)
将该语句替换为:
if ("tablet".equals(deviceType))
这更好,因为当deviceType为null时,它不会抛出NullPointerException
注意:建议使用TextUtils也是多余的。“可能是多余的…”-谢谢,但我之所以这么问是因为我认为它是多余的,但需要确认。如果“.equals(deviceType)
是冗余的,为什么我要TextUtils.isEmpty
?