Reputation: 271
Why can't I properly retrieve from my hashtable? I create a hashtable which consists of key and values as both type Coordinate (a class I created). And then I can't retrieve the x value from my coordinates object.
public coordinates translateOffsetToPixel(int x, int y){
//Translate given coordinates to pixel coordinates for the cell
coordinates input = new coordinates(x,y);
coordinates outputPixelCoord;
Hashtable <coordinates, coordinates> table = new Hashtable<coordinates, coordinates>();
for (int r = 0 ; r<row; r++){
for(int c = 0; c< col; c++){
System.out.println("hit translation");
table.put(new coordinates(r,c), new coordinates(r*2,c*2));
}
}
outputPixelCoord = table.get(input);
System.out.println("outputX:" + outputPixelCoord.getX()); //ERROR
return outputPixelCoord;
}
Coordinates Class:
public class coordinates {
private int x,y;
public coordinates(int x, int y){
this.x = x;
this.y = y;
}
public int getX() {return x;}
public int getY() {return y;}
}
LOGTABLE:
03-17 13:55:53.690 1961-1961/com.example.sam.matrix D/ViewRootImpl﹕ ViewPostImeInputStage ACTION_DOWN
03-17 13:55:53.780 1961-1961/com.example.sam.matrix I/System.out﹕ hit board
03-17 13:55:53.780 1961-1961/com.example.sam.matrix I/System.out﹕ 5
03-17 13:55:53.780 1961-1961/com.example.sam.matrix I/System.out﹕ hit translation
03-17 13:55:53.780 1961-1961/com.example.sam.matrix E/InputEventReceiver﹕ Exception dispatching input event.
03-17 13:55:53.780 1961-1961/com.example.sam.matrix E/MessageQueue-JNI﹕ Exception in MessageQueue callback: handleReceiveCallback
03-17 13:55:53.800 1961-1961/com.example.sam.matrix E/MessageQueue-JNI﹕ java.lang.NullPointerException
Upvotes: 0
Views: 76
Reputation: 1025
You need to override the hashCode and equals method like so, so that it may be stored and retrieved from the HashTable/HashMap, etc..
public class Coordinates {
private int x,y;
public coordinates(int x, int y){
this.x = x;
this.y = y;
}
public int getX() {return x;}
public int getY() {return y;}
public int hashCode() {
// This is just a random way to generate hash
// see other ways to generate hash before you implement this
return x + (37 * y)
}
public boolean equals(Object obj) {
if (obj instance of Coordinates) {
Coordinates c = (Coordinates)obj;
return c.x == this.x && c.y == this.y;
}
return false;
}
}
Upvotes: 1
Reputation: 178333
For a Hashtable
(and HashMap
) to store and retrieve keys properly, the key type must override hashCode
and equals
properly.
To successfully store and retrieve objects from a hashtable, the objects used as keys must implement the hashCode method and the equals method.
You haven't overridden those methods, so the Hashtable
can't find your keys. Override those methods.
Upvotes: 1