M
M
Mimocodil2021-04-14 13:22:45
Java
Mimocodil, 2021-04-14 13:22:45

Why is using .equals(null) bad?

Recently completed my first java project. I was looking for a code review and found out about the existence of static code analyzers, like findbugs. Installed SpotBugs Eclipse Plugin and instructed to check my project. He found a bug that I don't understand.

Based on the JButton, I made a round button and wrote a color assignment function for it (class variable color_normal), which also assigns a "reverse" color (color_pressed) to the pressed state.

public void setColor(Color c) {
  color_normal = c.equals(null) ? Color.WHITE : c;
  color_pressed = c.equals(null) ? Color.GRAY : new Color(255 - color_normal.getRed(), 255 - color_normal.getGreen(), 255 - color_normal.getBlue());
}


Bug Report:
Bug : Call to equals(null) in guijcalc.ui.CircleButton.setColor(Color)
This method calls equals(Object), passing a null value as the argument. According to the contract of the equals() method, this call should always return false.
Rank : Scary (9), confidence : Normal
Pattern : EC_NULL_ARG
Type : EC, Category : CORRECTNESS (Correctness)


Why is using .equals(null) bad? Is it different from obj == null in this context? Or maybe there is a better way?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Denis Zagaevsky, 2021-04-14
@Ezekiel4

Well, it's written there, have you even read it? Let me quote:

This method calls equals(Object), passing a null value as the argument. According to the contract of the equals() method, this call should always return false.

Even the online translator did it .
In your case it is necessary to write c == null ? Color.WHITE : c;
It is also better to use some of the NonNull/Nullable annotations.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question