Created
March 22, 2021 02:30
-
-
Save amaembo/137a489ec49a253a644fd6964385616c to your computer and use it in GitHub Desktop.
Break HashSet with incorrect compareTo implementation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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