Interview Question for Software Engineer / Developers






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

The sole purpose of hashcode() is to come up with efficient way of finding Hash buckets. Once a bucket is determined the overridden equals method can be used to retrieve that element.

Without hashcode method, all the elements can be inside a single bucket and hence result in inefficient hashes.

- Amrut March 14, 2010 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

Actually, the .hashCode() method will have its default behavior, which in general produces different hashes for objects that compare equal. This is problematic for (e.g.) HashSet, which can mistakenly conclude that an object is not in the set when in fact there was an equal element in a bucket other than the one searched.

- Anonymous March 14, 2010 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

1)Assume, the equals method is overridden correctly and hashcode is left to default implementation. Now

EqualsOnlyObject o1 = new EqualsOnlyObject();
    HashSet hs = new HashSet();
    EqualsOnlyObject o2 = o1.clone();  //As per equals, o1 == o2 (but what abt hashcode?)
    hs.Add(o1);  //Added successfully
    hs.Add(o2);  //this too is added successfully(default hashcode is unique, as  its mostly the memory address of the object)
    PRINT hs.Count();  //should print "2"

2)But assume if the hashcode is overridden properly then hs.Add(o2) should not add the object "o2" since they are identical.

- Thiyanesh March 15, 2010 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

To obey rule i.e if two objects are equal,it means their hash codes are equal. Just imagine an object with 3 properties and respective class has equals method definition which considers only 2 proprieties out of 3. then we should implement hashcode() also by using same prosperities.

- raghava.javvaji September 23, 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