1 Reply Latest reply: Aug 6, 2009 8:59 AM by 796125 RSS

    Comparator question - changing Equals and HashCode too?

    800467
      Hi all I have an object test - this contains 2 variables:
      Int a; and Int b;
      Then there is a method called test() which returns a double and looks like this:
      public Double test()
      {
      return a * (1d / b);
      }
      I have implemented the compareTo method do the "compareTo" test using the call to test() not on the fields directly e.g.
      this.test().compareTo(anotherObject.test())
      instead of
      if (this.a != null && anotherDateInterval.a != null)
              {
                  compareTo = this.a.compareTo(anotherDateInterval.a);
              }
      Because I using the test() in the compareTo do I need to change the equals and hashcode method as well to reflect the use of test()?
      e.g.
      public boolean equals(Object obj)
      {
         if (test() == null)
              {
                  if (other.test() != null)
                  {
                      return false;
                  }
              }
              else if (!test().equals(other.test()))
              {
                  return false;
              }
      }
        • 1. Re: Comparator question - changing Equals and HashCode too?
          796125
          That depends if there are any class invarients that can be depended upon.

          The basic rule is that if .equals() returns true, then .compareTo() must return 0, but not necessarily the other way around. As long as this holds true, you don't really have to change .equals() or .hashCode(). If you're still using the identity equals method, then you probably don't have to worry about it. If you've overridden .equals() to be dependent upon a and b in some way, you probably do have to change the way .equals() works to make sure that .equals() doesn't return true if .compareTo() doesn't return 0.

          - Adam