Why does comparing enums using == cause a PMD warning?

Next, two enum values โ€‹โ€‹are compared using == :

 MyEnum enum1 = blah(); // could return null MyEnum enum2 = blahblah() // could return null if (enum1 == enum2) { // ... } 

But PMD gives a CompareObjectsWithEquals warning on line 3:

Use equals () to compare object references

I'm not sure I understand the source code for this check , but I thought it would be nice to compare the two enumerations with == , so I wonder if the code can be improved or the check is wrong.

+6
source share
2 answers

This is really considered a mistake:

However, it seems difficult to catch all the possible cases (quote from a newer error):

This is a bit complicated, because to determine if a type is a Enum, we need type resolution.

I was able to configure a rule to check if the type of variables are Enum. This only works if Enum types are on the โ€œauxclasspathโ€ of pmd, so type resolution can find it.

Your isolation example still causes this false positive because PMD does not know what ProcessStatus is. I checked this with java.math.RoundingMode, which is always in the classpath and will be solved.

("Your example" refers to the ticket author, not the OP when the stack overflows)

Your case may work with PMD 5, the source you are associated with belongs to PMD 4.

Update: the current source contains an additional check for enumerations:

  // skip, if it is an enum if (type0.getType() != null && type0.getType().equals(type1.getType()) && type0.getType().isEnum()) { return data; } 
+18
source

It is good to use .equals() , because under the hoods , what happens is that the instances are compared with == .

 public final boolean equals(Object other) { return this==other; } 

Note that this implementation of .equals() is final , which means that you cannot override it in your enum.

+4
source

Source: https://habr.com/ru/post/989349/


All Articles