The problem which i posted is due to hashCode.
When a object of TestMap1 is created using new keyword, each time it refers it super class i.e, Object, so from the Super Class Object, it prints the hashCode while we use the following code snippet
Iterator iter = map.keySet().iterator();
while(iter.hasNext()){
System.out.println("iter : "+ iter.next().hashCode());
}
When you check with
System.out.println("map.get(new TestMap()1 : "+ map.get(new TestMap1()));
it is again creating another hashcode of Super Class Object. it will differnt now, because of differnt hashcode map doesn't find any object, so it returns a null.
To avoid all these problems, we need to implement hashCode method in the TestMap1 class like follows
public int hashCode()
{
return x;
}
I hope this will solve your problem. by doing this, the hashCode will always been dependent on the class TestMap1. So, when you create a new TestMap1() with default constructor, it will always returns a hashCode of 0 and you will get values from map.get(new TestMap1())
for your information, the full code is follows as
package com.scjp.test;
import java.util.HashMap;
import java.util.Iterator;
public class TestMap1{
private int x;
TestMap1(){
}
TestMap1(int x){
this.x = x;
}
@Override
public boolean equals(Object obj) {
if(((TestMap1)obj).x == this.x)
return true;
else
return false;
}
public int hashCode()
{
return x;
}
/**
* @param args
*/
public static void main(String[] args) {
System.out.println("can a hashmap hold two objects created newly as keys ?");
HashMap map = new HashMap();
map.put(new TestMap1(), new Integer(3));
map.put(new TestMap1(), new Integer(4));
Iterator iter = map.keySet().iterator();
while(iter.hasNext()){
System.out.println("iter : "+ iter.next().hashCode());
}
System.out.println("Size after insertion : "+ map.size());
map.put(new Integer(3),new TestMap1(3));
map.put(new Integer(3),new TestMap1(4));
System.out.println("Size after insertion : "+ map.size());
System.out.println("map.get(new TestMap()1 : "+ map.get(new TestMap1()));
}
}