Skip to content

Instantly share code, notes, and snippets.

@amaembo
Created March 22, 2021 02:30
Show Gist options
  • Save amaembo/137a489ec49a253a644fd6964385616c to your computer and use it in GitHub Desktop.
Save amaembo/137a489ec49a253a644fd6964385616c to your computer and use it in GitHub Desktop.
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