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 Interfaces

Jonathan Ramirez
Jonathan Ramirez
6,284 Points

How does the compiler know to implement compareTo() ?

Hi there,

How does the compiler know to implement compareTo() without you necessarily calling it?

Is it because you've written "@Override" which replaces the default code in the compareTo method with the code you've written?

  @Override
  public int compareTo(Object obj) {
    //First compare the tweets themselves. If at this top stage, they are indeed the same object, stop and return 0.
    Treet other = (Treet) obj;
    if (equals(other)) {
      return 0;
    }

    //It didn't pass the first test, so we compare by dates. Same dates (time stamp) are usually same tweet.
    int dateCmp = mCreationDate.compareTo(other.mCreationDate);
    if (dateCmp == 0) {
    return mDescription.compareTo(other.mDescription);
    }

    //if not, then show how much older, more recent the 'other' tweet is.

    return dateCmp;

  }

'''

1 Answer

La Gracchiatrice
La Gracchiatrice
4,615 Points

The compiler knows Because Treet implements the interface Comparable, this interface has an abstract method called compareTo()