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
Peter Kinsella
9,154 PointsEquals method?
I understand that an incoming object is being compared to the object that is currently in memory. However, if the mCreationDate and the mDescription date are the same, why use equals? it's doing nearly the same job?
1 Answer
Alexander Nikiforov
Java Web Development Techdegree Graduate 22,175 PointsThis is not correct
I understand that an incoming object is being compared to the object that is currently in memory.
Object on which compareTo is executed is compared to object that is passed in argument of method.
@Override
public int compareTo(Object obj) {
BlogPost bg = (BlogPost) obj;
// we compare "obj" casted to "bg" on the class where it is executed
// first we see if one object is equal to another one...
// one can use equals() method inherited by Object
// or can @Override this method
if (this.equals(bg)) {
return 0;
}
// if objects are not the same using equals we can use other
// properties of them to compare
// for example we can use compareTo method defined on
// java.util.Date so that we can compare creation date
// of "this" object to creation date of argument object "obj" casted
return this.mCreationDate.compareTo(bg.getCreationDate());
}
In the end when you write in Main
BlogPost bp1 = new BlogPost();
BlogPost bp2 = new BlogPost();
// we can compare one to other
bp1.compareTo(bp2);
There is a very well defined structure of how to write and why compareTo and we have to follow it...
This quote I don't understand at all, sorry, what do you mean?
However, if the mCreationDate and the mDescription date are the same, why use equals?
If the mCreationDate is the same for both objects than this.mCreationDate.compareTo(bg.getCreationDate()); will return 0, that is it
When we use equals we compare completely different things: we are using equals method for BlogPost class which implementation can be manually @Overriden, or left to be as is, inherited by Object