I am executing below code after overriding hashcode method of an object (BookMe). Aim is to override hashcode of the object which i will be using as a key in my map (hashmap). But, after executing I see null values. The is no problem with the actual size of map. below is the code. If I don't override hashcode method I get correct output (i mean all three values). `
class BookMe{
private String isbn ;
static int i = 0;
public BookMe(String isbn)
{
this.isbn = isbn;
}
public String getIsbnValue()
{
return this.isbn;
}
@Override
public boolean equals(Object o)
{
if(o instanceof BookMe && ((BookMe)o).getIsbnValue() == this.getIsbnValue())
{
return true;
}
else{
return false;
}
}
@Override
public int hashCode()
{
return this.isbn.toString().length() + (++i);
}
}
public class HashMapTest {
public static void main(String[] args) {
Map<BookMe, Integer> map = new HashMap<BookMe, Integer>();
BookMe b1 = new BookMe("Graham");
BookMe b2 = new BookMe("Graham");
BookMe b3 = new BookMe("Graham");
map.put(b1, 19);
map.put(b2, 33);
map.put(b3, 22);
System.out.println("----444444--------");
System.out.println(map.size());
Set <BookMe> set = map.keySet();
System.out.println("------*****------");
for(BookMe bk : set)
{
System.out.println("bk : "+ bk);
System.out.println(map.get(bk));
}
}
} `