Using Points As Keys For HashTables Always Returns Nulls

Jackson Ennis :

I'm trying to use a hashtable to store and retrieve values for indices of a matrix.

Hashtable<Point, Integer> sparseMatrix = new Hashtable<Point, Integer>();

Each point has an x and a y, with an override function for toString to make it comprehensible.

public class Point {

    int x, y;
    public Point(int x, int y) {
        this.x = x;
        this.y = y;
    }

    public int[] pos() {
        return new int[] {x, y};
    }

    public int[] reverse() {
        return new int[] {y, x};
    }

    @Override
    public String toString() { 
        return String.format(x + "," + y); 
    } 

}

When you print out the hashtable, you get {1,1=7, 2,1=9, 1,2=8, 3,1=11, 3,2=12, 2,2=10} so I definitely know that values are being stored, and the keys are being formatted the way I want.

So, why, when I type sparseMatrix.contains((new Point(1,1))) I always receive false despite clearly having a value there?

I feel like there is something fundamental I'm missing about identity.

WJS :

You need to override hashCode and equals for your key to work properly.

public int hashCode() {
}

public boolean equals(Object o) {
}

Read the Map interface description here for details.

I modified your class to add the methods. You should still read about it ensure you understand the issues.

class Point {

    int x, y;
    public Point(int x, int y) {
        this.x = x;
        this.y = y;
    }

    @Override
    public int hashCode() {
         return x*31 + y;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (o instanceof Point) { 
           Point p = (Point) o;
           if (p.x == this.x && p.y == this.y) {
               return true;
           }
        }
        return false;
    }
    public int[] pos() {
        return new int[] {x, y};
    }

    public int[] reverse() {
        return new int[] {y, x};
    }

    @Override
    public String toString() { 
        return String.format(x + "," + y); 
    } 
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=16556&siteId=1