JDK-7030899 : (coll) TreeSet uses the wrong method for equality detection during add(E)
  • Type: Bug
  • Component: core-libs
  • Sub-Component: java.util:collections
  • Affected Version: 6u24,7
  • Priority: P4
  • Status: Resolved
  • Resolution: Not an Issue
  • OS: linux,windows_7
  • CPU: x86
  • Submitted: 2011-03-24
  • Updated: 2013-09-10
  • Resolved: 2013-09-10
The Version table provides details related to the release that this issue/RFE will be addressed.

Unresolved : Release in which this issue/RFE will be addressed.
Resolved: Release in which this issue/RFE has been resolved.
Fixed : Release in which this issue/RFE has been fixed. The release containing this fix may be available for download as an Early Access Release or a General Availability Release.

To download the current JDK release, click here.
JDK 8
8Resolved
Related Reports
Duplicate :  
Relates :  
Description
FULL PRODUCT VERSION :


A DESCRIPTION OF THE PROBLEM :
http://download.oracle.com/javase/6/docs/api/java/util/TreeSet.html#contains%28java.lang.Object%29 states that add(E) uses the equals method to determine whether two objects were equal. However, I have determined that it only uses compareTo, which does not make sense in this context. Originally, I had a compareTo that was inconsistent with the equals method because I was only using it to sort elements by a unique identifier. I put a print statement at the beginning of the equals method and it printed nothing for the 500+ times the add method for TreeSet had been run. Adding the following line to the compareTo method fixed this problem and made the TreeSet detect duplicates correctly: if (this.equals((Clause) o)) return 0;


REPRODUCIBILITY :
This bug can be reproduced always.

CUSTOMER SUBMITTED WORKAROUND :
make compareTo consistent with equals

Comments
Per the TreeSet Javadoc, "Note that the ordering maintained by a set (whether or not an explicit comparator is provided) must be consistent with equals if it is to correctly implement the Set interface. (See Comparable or Comparator for a precise definition of consistent with equals.) This is so because the Set interface is defined in terms of the equals operation, but a TreeSet instance performs all element comparisons using its compareTo (or compare) method, so two elements that are deemed equal by this method are, from the standpoint of the set, equal. ". The compareTo() and equals() must be consistent to operate as you expect.
10-09-2013

EVALUATION Effectively the same documentation problem as CR # 6579200
05-04-2011