"==" 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
Compliant Solution
String类不会犯错误,主要是一些数值类型的包装类对象在进行比较的时候不要使用"==或!=
原始数据类型才使用==或!=进行比较!!
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){//禁止使用这种写法 //... }
原始数据类型才使用==或!=进行比较!!
相关文章推荐
- SonarQube-Java规范之Atomic-".equals()" should not be used to test the values of "Atomic" classes
- Linux下开发warning:"the `gets' function is dangerous and should not be used"
- "Calendars" and "DateFormats" should not be static
- "Calendars" and "DateFormats" should not be static
- warning: the 'gets' function is dangerous and should not be used.的解决办法
- What is an abstract class, and when should it be used?
- "enum" fields should not be publicly mutable
- the update-modules command is deprecated and should not be used
- " 'this' may not be used in this context"
- Synchronized classes Vector, Hashtable, Stack and StringBuffer should not be used
- The function equals must be used with a prefix when a default namespace is not specified
- Why the "volatile" type class should not be used
- iOS 整型转换警告"NSInteger' should not be used as format arguments; add an explicit cast to 'long' inste"
- 消除警告"property access result unused - getters should not be used for side effects"
- the `gets' function is dangerous and should not be used.
- warning: the gets function is dangerous and should not be used.
- The function equals must be used with a prefix when a default namespace is not specified解决
- Artifact has not been packaged yet. When used on reactor artifact, unpack should be executed after p
- warning: the 'gets' function is dangerous and should not be used.的解决办法
- warning: the 'gets' function is dangerous and should not be used.的解决办法