Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bad practice - Class defines compareTo(...) and uses Object.equals()

Tags:

java

sonarqube

Wondering what needs to be done for listed method

 public final int compareTo(final FieldDTO o) {
        return o.available.compareTo(this.available);

its throwing exception on line 2 stating Bad practice - Class defines compareTo(...) and uses Object.equals() 16 days
field defines compareTo(FieldDTO) and uses Object.equals()

Not sure how should i handle this. Thanks in advance.

like image 411
Maulzey Avatar asked May 22 '13 20:05

Maulzey


2 Answers

If you define compareTo you should at least define equals

boolean equals(it) { 
  return compareTo(it) == 0; 
} 

otherwise you will get strange problems when you put your object in Maps and Sets. It is generally good practice to also define hashCode.

like image 167
OldCurmudgeon Avatar answered Oct 12 '22 23:10

OldCurmudgeon


you need to override Object class equals() and hashCode() methods. Use IDE generated code for these, it will pull all the Object attributes and creates method for you.

On eclipse IDE:

  1. Right click on the class
  2. Select Source
  3. Generate hashCode() and equals()...
like image 22
Raj Pandiri Avatar answered Oct 12 '22 23:10

Raj Pandiri