Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Break HashSet with incorrect compareTo implementation
import java.util.*;
class BreakHashSet {
public static void main(String[] args) {
Point[] points = new Point[20];
Arrays.setAll(points, idx -> new Point(idx * 500_000_000,
-new Point(idx * 500_000_000, 0).hashCode()));
Set<Point> set = new HashSet<>(Arrays.asList(points));
set.remove(points[1]);
System.out.println(set.contains(points[14])); // Prints false!
}
}
record Point(int x, int y) implements Comparable<Point> {
@Override
public int compareTo(Point o) {
if (x != o.x) {
return x - o.x;
}
return y - o.y;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment