HashSet.contains not working as expected?

I have a HashSet<Face>. Here's face:
private static class Face {
public Vertex[] vertices;

public Face(Vertex[] vertices) {
this.vertices = vertices;
}

@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Face face = (Face) o;
return Arrays.deepEquals(Arrays.stream(vertices)
.sorted(Comparator.comparingInt(v -> Arrays.hashCode(v.vertex)))
.toArray(Vertex[]::new), Arrays.stream(face.vertices)
.sorted(Comparator.comparingInt(v -> Arrays.hashCode(v.vertex)))
.toArray(Vertex[]::new));
}

@Override
public int hashCode() {
return Arrays.hashCode(vertices);
}

@Override
public String toString() {
return "Face{" +
"vertices=" + Arrays.toString(vertices) +
'}';
}
}
private static class Face {
public Vertex[] vertices;

public Face(Vertex[] vertices) {
this.vertices = vertices;
}

@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Face face = (Face) o;
return Arrays.deepEquals(Arrays.stream(vertices)
.sorted(Comparator.comparingInt(v -> Arrays.hashCode(v.vertex)))
.toArray(Vertex[]::new), Arrays.stream(face.vertices)
.sorted(Comparator.comparingInt(v -> Arrays.hashCode(v.vertex)))
.toArray(Vertex[]::new));
}

@Override
public int hashCode() {
return Arrays.hashCode(vertices);
}

@Override
public String toString() {
return "Face{" +
"vertices=" + Arrays.toString(vertices) +
'}';
}
}
If I create "idential" faces (the texCoords and vertex order aren't same, but have same vertices), Face.equals returns expected value. However, if I do that for a HashSet, it doesn't work. An ArrayList works fine, but I need a Set. What can I do to fix?
4 Replies
JavaBot
JavaBot9mo ago
This post has been reserved for your question.
Hey @The Typhothanian! Please use /close or the Close Post button above when your problem is solved. Please remember to follow the help guidelines. This post will be automatically closed after 300 minutes of inactivity.
TIP: Narrow down your issue to simple and precise questions to maximize the chance that others will reply in here.
0x150
0x1509mo ago
you implement the hashCode properly
No description
0x150
0x1509mo ago
this ^ is the implementation of Arrays.hashCode the hash code you get depends on which element is where your equals sorts those elements (bad idea), so the equals is functionally different to hashCode -> you broke the general contact between those two -> Hash-optimized collections or similar things will behave wonky
JavaBot
JavaBot9mo ago
💤 Post marked as dormant
This post has been inactive for over 300 minutes, thus, it has been archived. If your question was not answered yet, feel free to re-open this post or create a new one. In case your post is not getting any attention, you can try to use /help ping. Warning: abusing this will result in moderative actions taken against you.
Want results from more Discord servers?
Add your server