Fix type safety issues in sorted collections #15
Merged
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
The treap-based collections are split into hashed and sorted variants. The hashed collections are the most versatile; they'll work for any key type. The sorted collections are specific to
Comparable
types, taking advantage of the ordering to avoid having to deal with hash collisions.We don't expose the notion of sorted vs hashed in the public API. Instead, we automatically create the correct collection type based on the element type. This mostly works, but has some issues currently. Take the following for example:
This is allowed statically (
treapSetOf
has no restrictions on the element type), but currently throws aNullPointerException
at runtime. The reason is that the first element isComparable
, and so we create aSortedTreapSet
, which is effecively aTreapSet<Comparable<T>>
Then, when we add thenull
, we fail the runtime check that the element is aComparable<T>
, because it is null.Similarly, if we start with a
Comparable
, and then add a non-Comparable
, we also crash:Where we went wrong is in making
SortedTreapSet
aTreapSet<Comparable<T>>
. Conceptually,SortedTreapSet
should be a set of arbitrary values - that just happens to only contain values that areComparable
.We fix this by removing the constraint from
SortedTreapSet
(andSortedTreapMap
), and adding some runtime checks to switch to the hashed collections if a non-Comparable
key is added.We also allow
null
as a sorted key, which prevents the (quite expensive) downgrade to the hashed collections just to get nullability.