hm.get(new Coordinates(x, y - 32))
returns null in your case. and hence
hm.get(new Coordinates(x, y - 32)).equals
means calling a method on null throws NPE.
why hm.get(new Coordinates(x, y - 32))
returns null in your case ?
when you add key to the hashmap, it creates a hashcode for that and stores it in its cache and while retrieving it refers to the corresponding hashcode available in the cache.
so while adding new coordinates , cordinate object hashcode will be added to hashmap.
in your case cordinate class has not overriden hashcode and equlas method properly.
hence when you create new coordinate object its hashcode will be different for each object even though they are identical.
so even if you create 2 identical object , your hashcode for 2 identical cordinate object will be different because no hashcode overriden and hence Object class hashcode is taken.
How to Avoid this
Override hashcode method inside your coordinate class considering all the attributes for hashcode
and use prime number for calculation
public int hashCode()
{
return 31*x+y;
}
and override equals method as below
public boolean equals(Object obj)
{
if(obj == null)
return false;
if (!(obj instanceof this))
return false;
Coordinates cordinate= (Coordinates)obj;
return x == cordinate.getX() && y == cordinate.getY();
}
So now when you create 2 identical object their hashcode remains the same and while entering those object as key to map, it identifies them as identical.
and if you retrieve value from map by passing key as a new object(which is identical with attributes to the already inserted key) then it gets the value which is not null.
Final Point
hm.put(new Coordinates(x, y - 32),"value");
here new coordinate object has been created , its hashcode is cached by hashmap which will be used later for comparing while retriveing.
hm.get(new Coordinates(x, y - 32));
this will also creates a new coordinate object and its hashcode will be same if we have overriden the hashcode and hence it gets the value and retunns "value" for us.
if not overriden then its new hashcode value will be different and while retriving hashmap searches in its cache but not available and hence returns null.
so make sure hashcode and equals method are properly overriden on the cordinate class.