Uploaded image for project: 'Rules Repository'
  1. Rules Repository
  2. RSPEC-2141

Classes that don't define "hashCode()" should not be used in hashes

    XMLWordPrintable

    Details

    • Type: Bug Detection
    • Status: Active
    • Resolution: Unresolved
    • Labels:
      None
    • Message:
      Add a "hashCode()" method to "className" or remove it from this hash.
    • Default Severity:
      Major
    • Impact:
      Low
    • Likelihood:
      High
    • Covered Languages:
      Java
    • Remediation Function:
      Constant/Issue
    • Constant Cost:
      15min
    • Analysis Scope:
      Main Sources
    • Implementation details:
    • FindBugs:
      HE_USE_OF_UNHASHABLE_CLASS, HE_SIGNATURE_DECLARES_HASHING_OF_UNHASHABLE_CLASS

      Description

      Because Object implements hashCode, any Java class can be put into a hash structure. However, classes that define equals(Object) but not hashCode() aren't truly hash-able because instances that are equivalent according to the equals method can return different hashes.

      Noncompliant Code Example

      public class Student {  // no hashCode() method; not hash-able
        // ...
      
        public boolean equals(Object o) {
          // ...
        }
      }
      
      public class School {
        private Map<Student, Integer> studentBody = // okay so far
                new HashTable<Student, Integer>(); // Noncompliant
      
        // ...
      

      Compliant Solution

      public class Student {  // has hashCode() method; hash-able
        // ...
      
        public boolean equals(Object o) {
          // ...
        }
        public int hashCode() {
          // ...
        }
      }
      
      public class School {
        private Map<Student, Integer> studentBody = new HashTable<Student, Integer>();
      
        // ...
      

        Attachments

          Issue Links

            Activity

              People

              Assignee:
              Unassigned Unassigned
              Reporter:
              ann.campbell.2 Ann Campbell
              Votes:
              0 Vote for this issue
              Watchers:
              2 Start watching this issue

                Dates

                Created:
                Updated: