Bug 114791

Summary: [DCR] warn on equals overrides that are not associated with a hashCode override
Product: [Eclipse Project] JDT Reporter: Maxime Daniel <maxime_daniel>
Component: CoreAssignee: JDT-Core-Inbox <jdt-core-inbox>
Status: VERIFIED DUPLICATE QA Contact:
Severity: enhancement    
Priority: P3 CC: david_audel, markus.kell.r
Version: 3.2   
Target Milestone: 3.5 M3   
Hardware: PC   
OS: Linux   
Whiteboard:

Description Maxime Daniel CLA 2005-11-02 12:01:12 EST
The JDK documentation states that any class that overrides Object.equals(Object)
should also override Object.hashCode() so as to enforce the specifics of
hashCode() contract (more precisely, for any two objects o1 and o2, if
o1.equals(o2) is true, then o1.hashCode() and o2.hashCode() must yield equal int
values; Object.equals(Object) only returns true for objects that are equal
according to ==, and Object.hashCode() is most often unsuitable for types that
define larger equivalence classes).
The compiler could raise a warning to help enforce this rule. 

As an example, the following code:
class X {
  int f1;
  X (int f1) {
	  this.f1 = f1;
  }
  @Override
  public Object clone() {
	  X result = new X(this.f1);
	  return result;
  }
  @Override
  public boolean equals(Object o) {
	  if (o == this) {
		  return true;
	  }
	  if (o instanceof X) {
		  return ((X) o).f1 == this.f1;
	  }
	  return false;
  }
  public static void main(String args[]) {
	  X x1 = new X(1), x2 = (X) x1.clone();
	  System.out.println(x1.equals(x2));
	  System.out.println(x1.hashCode() == x2.hashCode());
  }
}

currently prints:
true
false

on my machine (but could do something different for the second line, depending
on the JRE in use).
Comment 1 Markus Keller CLA 2005-11-17 04:22:23 EST
A dup of bug 38751, I'd say.
Comment 2 Maxime Daniel CLA 2005-11-17 05:06:27 EST
I agree.
Comment 3 Olivier Thomann CLA 2006-10-06 16:58:08 EDT

*** This bug has been marked as a duplicate of 38751 ***
Comment 4 David Audel CLA 2008-10-28 10:24:44 EDT
Verified for 3.5M3 using I20081026-2000 build.