Interview Question


Country: India




Comment hidden because of low score. Click to expand.
1
of 1 vote

There really is no contract between compareTo() and equals().

The recommended practice is that the hashCode() method should always be overridden, if the equals() method is overridden. May be, this question was aimed at confusing the interviewee.

- Prashant May 09, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

what if the class overrides equals and has some definition of equals() and at the same time implements comparable and compareTo() method gives some other implementation?

i.e obj.comapreTo(obj2) == 0 and obj.equals(obj2) is false?

- shine May 09, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

There would still not be any problem. What you are talking about is a logical error in the program.

When you override compareTo(), you are specifying the relative ordering of elements in a collection. When you sort the elements in the collection, it's the compareTo() definition which is looked up to determine the relative order of elements. How you override equals() doesn't have any effect on the way elements get sorted.

On the other hand, if you override equals() and fail to override hashCode(), all HashMap based collections which store this object would not behave correctly. For example, if you fail to override hashCode(), 2 logically equal objects would have different hash codes and would map to 2 different keys in the HashMap instead of referring to just 1 key.

- Prashant May 10, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

compareTo and equals also play a role when you insert objects in TreeSet as this maintains order, where compareTo is being used.

- GopalKrishna July 20, 2012 | Flag Reply


Add a Comment
Name:

Writing Code? Surround your code with {{{ and }}} to preserve whitespace.

Books

is a comprehensive book on getting a job at a top tech company, while focuses on dev interviews and does this for PMs.

Learn More

Videos

CareerCup's interview videos give you a real-life look at technical interviews. In these unscripted videos, watch how other candidates handle tough questions and how the interviewer thinks about their performance.

Learn More

Resume Review

Most engineers make critical mistakes on their resumes -- we can fix your resume with our custom resume review service. And, we use fellow engineers as our resume reviewers, so you can be sure that we "get" what you're saying.

Learn More

Mock Interviews

Our Mock Interviews will be conducted "in character" just like a real interview, and can focus on whatever topics you want. All our interviewers have worked for Microsoft, Google or Amazon, you know you'll get a true-to-life experience.

Learn More