ljeabmreosn
ljeabmreosn

Reputation: 980

Java TreeSet Not Working as Expected

I built my own class that implements comparable (maybe not relevant) and when I try using a HashSet to store the items, the HashSet sometimes claims that the item is in the HashSet even though it is not. I thought it had to do with reference checks, but I confirmed that is does not. What is wrong?

Vertex class equals and getHashcode:

public class Vertex implements Comparable<Vertex>{

    // some code ...

    @Override
    public boolean equals(Object obj) {
        Vertex other = (Vertex) obj;
        return this.getPosition().equals(other.getPosition());
    }


    @Override
    public int hashCode() {
        int hashCode1 = Integer.parseInt(this.getPosition().getX() + "" + this.getPosition().getY());
        return hashCode1;
    }
}

Position class:

public class Position {
    private int x;
    private int y;


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

    public int getX() {
        return x;
    }

    public int getY() {
        return y;
    }

    @Override
    public boolean equals(Object obj) {
        Position other = (Position) obj;
        return this.x == other.x && this.y == other.y;
    }

    @Override
    public String toString() {
        //return String.format("x = %d, y = %d", x, y);
        return String.format("(%d, %d)", x, y);
    }
}

EDIT: Here is the implementation

public static void test(Vertex[][] grid) {
    TreeSet<Vertex> someSet = new TreeSet<Vertex>(){{
       add(new Vertex(new Position(3, 4), false));
        add(new Vertex(new Position(0, 5), false));
    }};
    Vertex v = new Vertex(new Position(2, 5), false);
    if (someSet.contains(v)) {
        System.out.println("error");
    } else {
        System.out.println("ok");
    }
}

The above prints error.

Upvotes: 1

Views: 207

Answers (2)

ljeabmreosn
ljeabmreosn

Reputation: 980

I figured out the problem. As @NicolasFilotto pointed out, I did not mention the compareTo function. Based on a past post, TreeSet does not use hashCode but rather uses compareTo (I assume for binary searching). That is why my test cases were failing.

Upvotes: 1

OldCurmudgeon
OldCurmudgeon

Reputation: 65803

With your hashcode calculation the points (1,12) and (11,2) will be treated as identical.

See best-implementation-for-hashcode-method for advice on hash codes.

Upvotes: 0

Related Questions