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 - Retired Organizing Data Comparable

edumorlom
edumorlom
4,073 Points

Why did we have to if equal return 0, doesn't the compareTo method already do that?

The compareTo() method returns: -1 1 0 if they are equal.

Why did we have to check for equality in the method when overriding the method and return 0 if true? Doesn't the compareTo method already do that? Im confused.

Here's my code.

@Override
  public int compareTo(Object obj ) {
    BlogPost post = (BlogPost) obj;
    if (equals(post)) { //<-----------changed this to match the video
      return 0;
    }
    return mCreationDate.compareTo(post.getCreationDate()); //Shouldn't this return 1, -1 or 0?
  }

1 Answer

Hello

@Override

Step 1

This line is a simple casting to BlogPost

BlogPost post = (BlogPost) obj;

Step 2

This block simply say if 'this object' equials post (meaning they both points to same address in memory

if (equals(post)) { //<-----------changed this to match the video

  return 0;

then return 0. there is no point in going any further.

Step 3

Now this next line happen only if the 'if' condition fails. in that case, "this" and Post are not same object.. Hence, we need to use this over-ridden equal method:

return mCreationDate.compareTo(post.getCreationDate()); //Shouldn't this return 1, -1 or 0?

Hope this helps. If this answers your question, please mark question as answered.