I think TreeSet and TreeMap only use compareTo to do 2 jobs:
- sort items
- make sure there’s no 2 equal items in the collection
I have class Event with 2 fields: id and time.
I want to sort collection of events by time, but make sure there’s no 2 items with the same id in the collection.
If I use TreeSet, it will sort by time for me because I only compare time in compareTo method.
But I must manually manage the unique of id when I add new items to the collection.
Is there a better way for this issue?
Example (simplified):
I have a list of events in the collection:
event1 = Event(id: 1, year: 2020)
event2 = Event(id: 2, year: 2019)
event3 = Event(id: 3, year: 2021)
The collection should be sorted in the following order:
event2 = Event(id: 2, year: 2019)
event1 = Event(id: 1, year: 2020)
event3 = Event(id: 3, year: 2021)
Now, I want to update event2 with new time: Event(id: 2, year: 2022).
The new collection should replace the old event2 and use the new one with new order:
event1 = Event(id: 1, year: 2020)
event3 = Event(id: 3, year: 2021)
event2 = Event(id: 2, year: 2022)
You can see the code, which does not ensure the uniqueness of id here:
https://pl.kotl.in/7KlbEeDQ3
class Event(val id: Int, val year: Int): Comparable<Event> {
override fun equals(other: Any?): Boolean {
return other is Event && id == other.id && year == other.year
}
override fun hashCode(): Int {
return id
}
override fun toString(): String {
return "Event(id: $id, year: $year)"
}
override fun compareTo(other: Event): Int {
return year.compareTo(other.year)
}
}
fun main() {
val events = sortedSetOf(Event(1, 2020), Event(2, 2019), Event(1, 2021))
println("before:")
println(events.joinToString("\n"))
events.addAll(listOf(Event(2, 2022), Event(2, 2022), Event(2, 2022)))
println()
println("after (2 items with id 2, not what I want):")
println(events.joinToString("\n"))
}