• Post Reply Bookmark Topic Watch Topic
  • New Topic

Equals method  RSS feed

 
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why is this code is not compiling


(Jesper Young: Added code tags)
[ December 10, 2008: Message edited by: Jesper Young ]
 
Ranch Hand
Posts: 952
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
if ((this.Money+this.relatives)==((Person)O.Money+(Person)O.relatives))


This line has problem
((Person)O.Money+(Person)O.relatives))

you cannot do
((Person)O.Money


It is converting Money to Person means long to person.

you have to write
((Person)O).Money


the full line will be
if ((this.Money+this.relatives)==(((Person)O).Money+((Person)O).relatives))
 
Ranch Hand
Posts: 140
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Exactly. The downcast is not done properly in your code.
 
Java Cowboy
Sheriff
Posts: 16060
88
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to JavaRanch. Please use code tags when you post source code, this makes it easier to read.
 
Ranch Hand
Posts: 488
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to JavaRanch. Looks like your question was already answered... But, a tip for future reference would be that when you override the equals(Object) method you should always check whether Object is an instance of your class, like this:



The only other thing I would suggest is to avoid using Object O with a capital 'O' ... could easily get confused as the number zero.

hth, gl
 
Marshal
Posts: 56600
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You don't need if (...) return true; else return false; if you have a look at Sun's conventions �10.5.2 you can see a much more concise form.

If you use instanceof you can forget any problem with null values, which the equals method is supposed to handle. If you pass null to instanceof, you get false, which sorts it out.

If you extend the class and use instanceof in the equals methods, you can get serious errors. You can get mySuperclassObject.equals(mySubclassObject) returning true and mySubclassObject.equals(mySuperclassObject) returning false. You can sort that out using the getClass() method.


. . . obj != null && obj.getClass() == this.getClass() && . . .

That is much stricter and works as long as all objects are loaded with the same classloader. Note the != null call has to come first.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!