您的位置:首页 > 其它

"==" and "!=" should not be used when "equals" is overridden

2017-07-22 18:56 555 查看
It is equivalent to use the equality == operator and the equals method to compare two objects if the equals method inherited Object has not been overridden. In this case both checks compare the object references.

But as soon as equals is overridden, two objects not having the same reference but having the same value can be equal. This rule spots suspicious uses of == and != operators on objects whose equals methods are overridden.

Noncompliant Code Example

//String is a good example of a class overriding the equals method
String firstName = getFirstName();
String lastName = getLastName();
// Non-compliant, the two literals can have the same value and yet the condition is false
if (firstName == lastName) {
...
};


Compliant Solution

String firstName = getFirstName();
String lastName = getLastName();
if (firstName != null && firstName.equals(lastName)) {
...
};


String类不会犯错误,主要是一些数值类型的包装类对象在进行比较的时候不要使用"==或!=

Integer a = 2;
Integer b = 2;
if(a == b){//禁止使用这种写法
//...
}


原始数据类型才使用==或!=进行比较!!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐