Teacher Russell16,868 Points
Hi folks. I'm still a little confused about what we're using compareTo() for here. We're comparing the Treet to itself? Just a very basic explanation of what we're accomplishing in the end with this implementation and how it effects this program.
compareTo method takes an
Object as a parameter, this object is another
Treet (not the same as the treat the
compareTo was called on), this
Object is cast as a
Treet so that we can access its properties. Then the
Treet that the
compareTo method is called on is compared to the
Treet that was passed in to the method.
The goal of the method is to see if the
Treet that was passed in is equal, greater or lesser than the
Treet the method was called on. If the passed in
Treet is the same 0 is returned. If it is "greater" then a positive number is returned, if it is "lesser" then a negative number is returned.
The method is written like this because that is how the
compareTo method is supposed to act, according to the Comparable interface. When implementing an interface it's important to not just implement the required methods but to also make sure they follow the behavior the interface specifies.
The point of the method is that it allows other methods like
sort to sort arrays made up of a custom class like
Treet. Without this method it would have no idea how to sort
Treet objects as they have no natural order to them. With this method in place however it can easily compare them just by calling that method. And not just
Treet objects, the
sort method can work with all classes that implement the
Comparable interface, that is one of the benefits of interfaces. It allows you to have methods that can work with pretty much any class as long as they implement a specific interface. Which is often more efficient than having to write methods that only work with specific classes.
Sean M7,333 Points
I try to understand the concepts in simple words so it makes sense at another time.
The compareTo() method does exactly what it says. It compares something to something else.
In our example, it compares one treet to another treet, specifically by the date it was created.
Then when Arrays.sort(treets) is implemented, it sorts the treets in order by creation date.
Hope that made sense.
Sean M7,333 Points
I believe the answer to your question is mCreationDate because the question wants to sort the treets by the date it was created.