Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save antonlogvinenko/d38a48a479b6dc3262a90d84feaa03ac to your computer and use it in GitHub Desktop.
Save antonlogvinenko/d38a48a479b6dc3262a90d84feaa03ac to your computer and use it in GitHub Desktop.
Java Sorted Set
/*
* Just some X class
*/
public static class X implements Comparable<X> {
public int getX() {
return 42;
}
@Override
public int compareTo(X o) {
return 0;
}
}
/*
* Scenario 1: SortedSet with comparator
*/
SortedSet<X> s = new ConcurrentSkipListSet<X>(Comparator.comparingInt(X::getX));
SortedSet s2 = s;
s2.add("cake");
//ok
s2.add("cake");
s2.add("lie");
//java.lang.ClassCastException: java.lang.String cannot be cast to X
/*
* Scenario 2: SortedSet without comparator
*/
SortedSet<X> s = new ConcurrentSkipListSet<X>();
SortedSet s2 = s;
s2.add("cake");
//ok
s2.add("cake");
s2.add("lie");
//ok
s2.add("cake");
s2.add("lie");
s2.add(new X());
//java.lang.ClassCastException: java.lang.String cannot be cast to X
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment