Vivek Modi
10/19/2021, 8:25 AMfun main() {
val listOne = mutableListOf(2, 3)
listOne.add(0, 1)
println(listOne)
var listTwo = mutableListOf(2, 3)
listTwo = (mutableListOf(1) + listTwo).toMutableList()
println(listTwo)
}
what's the d/w both example?Rodrigo Lino
10/19/2021, 12:01 PMvar listTwo = listOf(2, 3)
listTwo = (listOf(1) + listTwo)
It would make more sense, and the drawbacks are time and memory since you would be allocating 2 more lists and copying the elements, this is the actual implementation of the plus operator:
public operator fun <T> Collection<T>.plus(elements: Iterable<T>): List<T> {
if (elements is Collection) {
val result = ArrayList<T>(this.size + elements.size)
result.addAll(this)
result.addAll(elements)
return result
} else {
val result = ArrayList<T>(this)
result.addAll(elements)
return result
}
}
But you would be dealing with immutability, which makes a few things easier.Vivek Modi
10/19/2021, 12:02 PMIvan Pavlov
10/19/2021, 12:38 PMkotlin.collections.ArrayDeque
or java.util.ArrayDeque
which have efficient insert operations at both ends (e.g. addFirst
)Syed Ovais Akhtar
10/19/2021, 1:00 PMVivek Modi
10/19/2021, 1:15 PMarrayDeques
Vivek Modi
10/19/2021, 1:17 PMkotlin.collections.ArrayDeque
. I am learning to how to improve my code. I don't know about any thingIvan Pavlov
10/19/2021, 1:27 PMkotlin.collections.ArrayDeque
is a particular implementation of MutableList
in kotlin. You can use it like any other implementation of MutableList
. Your example can be written with it like this:
val list: MutableList<Int> = ArrayDeque()
list.add(2)
list.add(3)
list.add(0, 1)
Vivek Modi
10/19/2021, 1:51 PMVivek Modi
10/19/2021, 2:15 PMaddFirst
cannot use in my this implemenation. But in kotlin doc https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/-array-deque/ addFirst
is there?Vivek Modi
10/19/2021, 2:15 PMIvan Pavlov
10/19/2021, 2:19 PMlist
variable has explicit MutableList
type
val list: MutableList<Int> = ArrayDeque()
If you change declaration to
val list: ArrayDeque<Int> = ArrayDeque()
or omit type
val list = ArrayDeque()
you'll see those methodsVivek Modi
10/19/2021, 2:21 PMval list: MutableList<Int> = ArrayDeque()
or val list: ArrayDeque<Int> = ArrayDeque()
Vivek Modi
10/19/2021, 2:22 PMlist.add(0, 1)
or list.addFirst(1)
Vivek Modi
10/19/2021, 2:23 PMIvan Pavlov
10/19/2021, 2:39 PMVivek Modi
10/19/2021, 2:41 PM