Kotlinlearncs.online LogoJava
Return to List

Test Writing: SimpleLinkedList set

Created By: Geoffrey Challen
/ Version: 2020.10.0

Let's implement a list using a different strategy. Instead of an internal array, we'll link items together into a chain using references. Our list class will only maintain a reference to the start of the list and walk the list to perform list operations. This approach will have interesting tradeoffs compared to our implementation that used arrays.

Starting with the SimpleLinkedList class below, complete the code for set. You'll want to review get and the rest of the code to understand how this list implementation works and how to walk a linked list.

Test Design Challenge

You're challenge is to write tests for this problem described above.

  • Provide a public class named TestSimpleLinkedList with a single non-private class method named test that accepts no arguments and does not return a value.
  • If the implementation of the class described above is incorrect, your test method should throw an exception.
  • If it is correct, do not throw an exception.
  • You may want to use Kotlin's assert or check methods
class SimpleLinkedList(values: Array<Any?>) {
private inner class Item(var value: Any?, var next: Item?)
private var start: Item? = null
private var size = 0
init {
for (value in values.reversed()) {
add(0, value)
}
}
fun size() = size
private fun add(
index: Int,
value: Any?,
) {
require(index == 0) { "Non-zero add not supported yet" }
start = Item(value, start)
size++
}
fun get(index: Int): Any? {
require(index in 0 until size)
var current = start
repeat(index) {
current = current!!.next
}
return current!!.value
}
fun set(
index: Int,
newValue: Any?,
) {
TODO("Not implemented")
}
}