Last active
May 27, 2017 18:02
-
-
Save antonlogvinenko/d38a48a479b6dc3262a90d84feaa03ac to your computer and use it in GitHub Desktop.
Java Sorted Set
This file contains 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
/* | |
* 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