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
colin Don
946 PointsI find this expression confusing: if (equals(Other) { ....}
I'm used to seeing equals method used in a format where one object is compared to another. e.g. if (firstName.equals(lastName) {....} and not if(equals(lastName) {....} Can someone please help me understand why equals method was used differently in the if condition.
2 Answers
Alexander Nikiforov
Java Web Development Techdegree Graduate 22,175 PointsIt is like a shortcut. When you write if(equals(lastName)) you actually mean to ask program to find method equals in this class and use it. Let me try to explain it in a different example first. Take a look at this code:
public class SomeClass {
public void method() {
}
public void otherMethodUsingMethod() {
// in order to use method() defined above we can write:
method();
// or we can write
this.method();
}
}
Coming back to equals():
public class SomeClass implements Comparable{
@Override
public boolean equals(Object o) {
// some code
return true;
}
@Override
public int compareTo(Object object) {
// Following two methods above are the same: they use method "equals" in this
// "SomeClass" defined above:
// 1. "verbose" version
if (this.equals(object)) {
// then do stuff
}
// 2. or we can write: without verbosity: use method "equals" in this "SomeClass" defined
// above
if (equals(object)) {
// same outcome
}
// Following third should be the same, but can be different because
// "equals" method of the "object" can have different implementation
if (object.equals(this)) {
// some code
}
return 0;
}
}
So coming back to question: method equals was not used differently: it was used just like any other method defined in this class...I hope it will make sense to you. Tried my best
Ilya Dolgirev
35,375 PointsNot only in conditions, actually. It is possible when this method is defined in the class you're inside.
colin Don
946 PointsMakes sense now. Thank you very much, Ilya.
colin Don
946 Pointscolin Don
946 PointsThank you very much, Alexander. That was very helpful.