wood burning stoves 2.0*
The moose likes Beginning Java and the fly likes equals overriding Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "equals overriding" Watch "equals overriding" New topic
Author

equals overriding

krishna bethanabhotla
Greenhorn

Joined: Nov 30, 2004
Posts: 15
Override java.lang.Object.equals in the following class, so that equality is based on values rather than references.

public class Simple {
private int digits;
private String text;

public Simple(int i, String s) {
digits = i;
text = s;
}
}
Can some body please provide the answer?
My answer is below:

Answer: public boolean equals(Object o){
if(!(o instanceof Simple)){
return false;
Simple simpl = (Simple)o;
return (simpl.digits == digits) && simpl.text.equals(text);
}
}
Layne Lund
Ranch Hand

Joined: Dec 06, 2001
Posts: 3061
First of all, the CODE button below the text entry area for a message creates two tags. Your code must go in between the tags in order to preserve the formatting.

Second, I doubt anyone here is willing to just give you the answer. However, we are more than happy to help you find the solution yourself. In fact, it looks like you are well on the way. Let's look at your proposed answer:

If you compile this, do you get any errors? I suspect you will get something about "unreachable code". This is because of the "return false;" statement. As soon as this is executed the method will return and the next two lines will never be executed. You can fix this by moving the closing brace:

With this fix, I think it should work as expected.

Keep Coding!

Layne


Java API Documentation
The Java Tutorial
krishna bethanabhotla
Greenhorn

Joined: Nov 30, 2004
Posts: 15
Layne,
You are right. I will make sure I wouldn't post these type of questions further.
Thanks for the answer and suggestion.
Layne Lund
Ranch Hand

Joined: Dec 06, 2001
Posts: 3061
Don't worry about it. This is the BEGINNER forum after all, so we don't expect particularly difficult questions. Just remember to show what you have tried on your own because as I said, most people here are unwilling to solve the problem for you. However, we are more than willing to point you in the right direction.

Good luck with your future programming projects!

Layne
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: equals overriding
 
Similar Threads
Which is best to use in hashcode?
Needs answers of some important questions
Correct implementation?? :confused:
Query
HashSet Duplicate element ?