The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes hashCode and equals implementation Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "hashCode and equals implementation" Watch "hashCode and equals implementation" New topic

hashCode and equals implementation

Pawanpreet Singh
Ranch Hand

Joined: Jun 12, 2005
Posts: 264

package collection;

import java.util.HashMap;
* @author PawanPreet

class Car
int model;
public Car(int model)

public boolean equals(Object obj)
if(obj instanceof Car && ((Car)obj).model==this.model)
return true;
return false;
public int hashCode()
return model;
public class HashEquals0 {

/** Creates a new instance of HashEquals */
public static void main(String... args)

Car car1= new Car(2005);

Car car2= new Car(2005);

Car car3= new Car(2006);

HashMap map = new HashMap();




System.out.println("map :"+map);
System.out.println("size :"+map.size());
System.out.println("2005(car1) :"+map.get(car1));
System.out.println("2005(car2) :"+map.get(car2));


output :

size :2
2005(car1) :ACCENT2
2005(car2) :ACCENT2

I have doubt that why size is not 3 as we have inserted 3 items. I have implemented hashCode and equals both. We know that two same items can go into one bucket. Does it depends on implementation of HashMap that it can have only one item (key-value) in not contain duplicates when hashCode() is implemented and provides same int value for equals object.

Could anybody explain actual fundamental behind this.
Stary Kapec
Ranch Hand

Joined: Dec 04, 2005
Posts: 81
We know that two same items can go into one bucket

No, HashMap does not accept duplicates. In fact two objects with the same hashCodes go into one bucket. There can be many different key objects in the same bucket. Two objects with same hashCodes are not considered same.

Car car1= new Car(2005);
Car car2= new Car(2005);

You created two objects that are meaningfully the same. Try equals on them. And then used them as keys in a HashMap that, as I said does not accept duplicates.


Above invocation returns the old value assigned previosly to the car1 key. Check it. You have just replaced the value of ACCENT1 by ACCENT2 assigned with car1, and have not add new entry.
[ July 31, 2006: Message edited by: Jasiek Motyka ]
I agree. Here's the link:
subject: hashCode and equals implementation
It's not a secret anymore!