Java Java Data Structures Exploring the Java Collection Framework Sets

Andre Kucharzyk
Andre Kucharzyk
4,479 Points

~11:36 "Returning 0 should only happen for true equality" - I have no idea what Craig meant there.

~11:36 "Returning 0 should only happen for true equality" - I have no idea what Craig meant there.

2 Answers

Tonnie Fanadez
Tonnie Fanadez
UX Design Techdegree Graduate 22,770 Points

The Set interface is responsible for ensuring no duplicate elements will be inserted in a Set subclass. Only unique elements can be inserted into a Set. If you want to add an element to the HashSet class you must first use the equals() and methods to verify that the element is unique. If 0 is returned then the compiler knows that the two Treets are equal because we have defined the equals() method.

With this in mind we need to check for true Equality on the compareTo() method to avoid dublicates on Set implementations .

Tonnie,

I understand that an element must be verified as unique before it can be added to a set. The part I'm confused about is "true equality". I wasn't aware that there was any kind of equality that wasn't "true". Does compareTo() not check for true equality? If it doesn't, then what exactly is it checking for and how does it differ from equals()?

Tonnie Fanadez
Tonnie Fanadez
UX Design Techdegree Graduate 22,770 Points

Hi william coleman

The compareTo () method defines the natural order; that is the default way for ordering objects of Treat class. The intent of the Treats comparison is to sort and see which Treat has higher priority over the other or which Treat come before the other.

compareTo () method doesn't really check for true equality. For true equality, we need to override the equals() and hashcode() method from the Object Class.

NB compareTo() method is from the Comparable interface and not from the Object Class.

Once again, thanks Tonnie. I seem to find your helpful answers all over the forums.