I’ve created a complex object in Java and I’m comparing it using the equals method.
Is this okay or is it preferred to give the object a name or an id and compare the objects names/ids?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
You should use the
equals()method. If you want to make equality a name and/or id comparison, do it inside theequals()method.It is the default way that Java determines equality.
Also, take a look at some of the answers for this question: Overriding the java equals() method quirk
There’s a relationship between
equals()andhashcode(). Both of these are used by Collections.