File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

hashCode and equals implementation

 
Pawanpreet Singh
Ranch Hand
Posts: 264
Eclipse IDE Java Spring
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
package collection;

import java.io.*;
import java.util.HashMap;
/**
*
* @author PawanPreet
*/

class Car
{
int model;
public Car(int model)
{
this.model=model;
}

public boolean equals(Object obj)
{
if(obj instanceof Car && ((Car)obj).model==this.model)
{
return true;
}
else
{
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();

map.put(car1,"ACCENT1");

map.put(car2,"ACCENT2");

map.put(car3,"ACCENT3");


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 bucket...do 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
Posts: 81
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.

map.put(car2,"ACCENT2");


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 ]
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic