Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Want hepl to understand Implementin an equals()

 
Deepak Bobal
Ranch Hand
Posts: 96
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In K @ B book of java5 on page 526 an example of Implementin an equals() method is given.I am getting problem to understand last few lines.

if ((o instanceof Moof) && (((Moof)o).getMoofValue()
== this.moofValue))
i am unable to understand the condition given after '&&'.
this.moofValue means moofvalue ,the current object holds.But what about (((Moof)o).getMoofValue()???
How they are different?/


Complete program is like this------

public class EqualsTest {
public static void main (String [] args) {
Moof one = new Moof(8);
Moof two = new Moof(8);
if (one.equals(two)) {
System.out.println("one and two are equal");
}
}
}
class Moof {
private int moofValue;
Moof(int val) {
moofValue = val;
}
public int getMoofValue() {
return moofValue;
}
public boolean equals(Object o) {
if ((o instanceof Moof) && (((Moof)o).getMoofValue()
== this.moofValue)) {
return true;
} else {
return false;
}
}
}




Thanks
Deepak
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15359
39
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In the equals() method, you are comparing the contents of the current object (on which the method is called) with the contents of some other object, that is passed to the method as an argument 'o'.

Looking at this expression:

(((Moof)o).getMoofValue()

You have 'o', which is an Object. To get the moofValue of that object, it first has to be cast to a Moof object, by doing (Moof)o. Then the method getMoofValue() is called on the casted object to retrieve the value. You can write this in multiple steps like this, I hope this makes it clear what the expression does to you:

Moof m = (Moof)o;
m.getMoofValue()

Looking at the complete expression:

if ((o instanceof Moof) && (((Moof)o).getMoofValue() == this.moofValue))

This is what happens:

1. Check that the object 'o' is really an instance of class Moof.
2. Get the moofValue from the object 'o'.
3. See if the moofValue from object 'o' and from the current object are equal.
[ February 15, 2008: Message edited by: Jesper Young ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic