Whilst developing simple primary queue in Kotlin I have bumped into an unchecked cast with an unchecked warning that I cannot get rid of:
private val pq: Array<T> = arrayOfNulls<Comparable<T>>(capacity) as Array<T>
Here is the full source code of the Kotlin priority queue:
class UnorderedMaxPQ<T : Comparable<T>>(capacity: Int) {
private val pq: Array<T> = arrayOfNulls<Comparable<T>>(capacity) as Array<T>
private var size = 0
fun isEmpty() = size == 0
fun size() = size
fun insert(x: T) {
pq[size++] = x
}
fun delMax(): T {
var max = 0
(1..size - 1)
.asSequence()
.filter { less(pq[max], pq[it]) }
.forEach { max = it }
exchange(pq, max, size - 1)
return pq[--size]
}
fun <T> exchange(a: Array<T>, i: Int, min: Int) {
val temp = a[i]
a[i] = a[min]
a[min] = temp
}
fun <T : Comparable<T>> less(c1: T, c2: T) = c1 < c2
}
Any suggestions on how to avoid the unchecked cast when creating an array of nulls?
Here is a simple unit test of the class above:
import org.hamcrest.core.Is.`is`
import org.junit.Assert.assertThat
import org.junit.Test
class UnorderedMaxPQTest {
@Test
fun insert_delMax() {
val pq = UnorderedMaxPQ<Int>(10)
pq.insert(2)
pq.insert(3)
pq.insert(4)
pq.insert(1)
assertThat(pq.delMax(), `is`(4))
assertThat(pq.delMax(), `is`(3))
assertThat(pq.size(), `is`(2))
pq.insert(10)
assertThat(pq.size(), `is`(3))
assertThat(pq.delMax(), `is`(10))
assertThat(pq.isEmpty(), `is`(false))
}
}
Edit 1:
You could re-write this:
private val pq: Array<T> = arrayOfNulls<Comparable<T>>(capacity) as Array<T>
as:
private val pq: Array<T> = Array<Comparable<T>?>(capacity, { null }) as Array<T>
The unchecked cast problem persists though. This variation is based on Andrey Breslav's post: https://stackoverflow.com/a/20297428/2735286