BriCode Thoughts from Brian Holt

9Feb/101

Java Checkstyle Covariant Equals Method Fix?

If some of you are as unfortunate as I am, your work or university forces you to use a script called Checkstyle that checks your code to see if it was "programmed well." While the script can provide valuable insight on how you clean up your code, it also often causes you to rewrite code that works perfectly well to only be more verbose than it needs to be.

One mishap I have encountered recently is the error "Covariant equals method" and it goes on to say that you're overwriting the equals method without providing and adequate hashCode method. The description from the sourceforge site is equally confusing

Checkstyle's Confusing Description

It seemed finicky at first because it didn't cite at first (when I had written the equals method) but it then it came up and would not go away. For those of facing similar issues, I offer the two solutions I found.

Solution 1:

The reason I got this error in the first place is because I had written an equals method in a parent class and then in again in a child class. The combination of the two, even though still functional, caused Checkstyle to go crazy. I solved the problem by just deleting the equals method in the child class and used only the one the parent class. You could do vice versa.

Solution 2:

If it is expedient to you to keep both equals methods in the parent and in the child class, all you need to do is to write a working hashCode method in the parent class. You could likely do it in the child class as well, but I have not tried that. A really easy way to make a working hashCode method is simply to use the one that Eclipse will make. Go to Source>Generate hashCode() and equals(). Worked like a charm for me.

Comments (1) Trackbacks (0)
  1. Sounds like a pain. Glad we didn’t use it.


Comments are closed.

No trackbacks yet.