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...

PSR
  • 39,804
  • 41
  • 111
  • 151

2 Answers2

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?

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
Mena
  • 47,782
  • 11
  • 87
  • 106
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;
    }
}
Ankur Singhal
  • 26,012
  • 16
  • 82
  • 116
  • 1
    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`. – lxcky Sep 05 '14 at 09:44
  • 1
    @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... – thkala Sep 05 '14 at 09:49