1
public class VO { public int hashcode() { return 0; } public boolean equals(Object obj) { return true; } public static void main(String args[]) { VO vo1 = new VO(); VO vo2 = new VO(); Map<VO,Integer> map = new HashMap<VO, Integer>(); map.put(vo1, 1); map.put(vo2, 1); System.out.println(map.size()); } } 

I am getting the output is :2

But as per my knowledge the output is 1.

When i am placing an element in map it will check the hashcode for the key,if that hashcode is same then it will go to check equals.If both the methods returns same it will override the previous value.

In my case both the methods are(hashcode and equals) returns 0 and true.So finally there must be one element in the map.But here i am getting size as 2.

What might be the reason.Thanks in dvance...

2
  • 2
    What about to add "override"? Commented Sep 5, 2014 at 9:37
  • @libik override means only one value will be there finally Commented Sep 5, 2014 at 9:48

2 Answers 2

11

You are not overriding Object.hashCode, you're implementing your own hashcode() method (mind the capitalized C).

A good practice is to always use @Override annotations when overriding. See: When do you use Java's @Override annotation and why?

Sign up to request clarification or add additional context in comments.

4 Comments

Thank u.I got it now.
It also helps to use the IDE code completion, instead of typing manually in such cases.
actually i wrote this is in normal notepad.I did not use IDE.That is the problem
@thkala so true. And with eclipse it's just about typing "hash" and pressing Ctrl-space, then enter :)
3

hashcode() (with small "c") was just acting as a normal method, and instead Object class method hashCode() was called.

public class VO { @Override public int hashCode() { return 0; } @Override public boolean equals(Object obj) { return true; } } 

2 Comments

Even if you don't put the @Override annotation, it will still override the same method in the superclass. In this case, the problem was the letter c in his hashcode method. It's suppose to be C.
@J.Lucky: true, but if you do put the annotation, modern Java compilers will let you know if you are not actually overridding or implementing anything...

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.