Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

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
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Tonnie Fanadez
UX Design Techdegree Graduate 22,796 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.

Tonnie Fanadez
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Tonnie Fanadez
UX Design Techdegree Graduate 22,796 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()?