TreeSets in java

  • 1 min read
  • Tags: 
  • java

Oh my god don't get me started on java's TreeSet implementation.

TreeSet's equals function is overriden by the compare function of the contained elements. If you want a sorted set, then "is this after that?" will be used for the answer of "are these two Sets equals?"

record Student(String name, int id) implements Comparable<Student> {
    @Override
    public int compareTo(@NotNull Student o) {
        // if you don't have absolutely all fields in this method, then you'll get some surprises.
        return Comparator.comparing(Student::id).compare(o, this);
    }
}

@Test
void test() {
    assertEquals(
            new TreeSet<>(Set.of(new Student("luca", 1))),
            new TreeSet<>(Set.of(new Student("not-luca", 1)))
    ); // this test does not fail at all.
}