PB.UEI
Use `equals()' when comparing two Objects
Description
This rule flags any case where "==" is used to compare two Objects.
The "==" operator is used to check if two Objects are the same instance of an object, and the '!=' operator used on an Object checks if two Objects are not two identical instances of an object. If you want to check if two Objects have the same value, you should use the `equals()' method.
Example
package PB;
import java.awt.*;
public class UEI {
public boolean CalculateEqual() {
boolean monthly = co.getSelectedItem() == "Monthly"; // Vio-
lation
return monthly;
}
public boolean CalculateNotEqual() {
boolean monthly = co.getSelectedItem() != "Monthly"; // Vio-
lation
return monthly;
}
private Choice co = null;
}
Repair
Change "==" to `equals()' as follows:
package PB;
import java.awt.*;
public class UEI {
public boolean CalculateEqual() {
boolean monthly = co.getSelectedItem().equals("Monthly");
return monthly;
}
public boolean CalculateNotEqual() {
boolean monthly = !(co.getSelectedItem().equals("Monthly"));
return monthly;
}
private Choice co = null;
}
Reference
Bloch, Joshua. Effective Java Programming Language Guide. Addison Wesley, 2001, pp.25 - 36.
|