Home > Blockchain >  Kotlin List<List<String>> when instantiating creates 1 empty element
Kotlin List<List<String>> when instantiating creates 1 empty element

Time:02-06

Solving algorithm tasks and came to one interesting situation that before I did not pay attention to.

Here is example:

 val testList1 = mutableListOf<String>()

    testList1.add("f")
    testList1.add("n")

    Toast.makeText(this, testList1.size.toString(), Toast.LENGTH_SHORT).show()

In this code, my toast will return size 2. Which is ok and expected. but let's take this example:

val testList2 = mutableListOf(mutableListOf<String>())

    testList2.add(mutableListOf("sf", "fgs"))
    testList2.add(mutableListOf("sw", "fgg"))

    Toast.makeText(this, testList2.size.toString(), Toast.LENGTH_SHORT).show()

Here the toast shows size = 3 even though I added 2 elements (2 lists). So when instantiating it adds 1 emptyList as the first element.

Not a big problem to solve this, we can just:

var finalList = testList2.removeIf { it.isEmpty() }

But I am curious why this happens. Also is there any nice way to avoid it. Would like to know little bit more if possible

CodePudding user response:

It is not strange that testList2 contains 3 objects. testList2 is constructed with an initial empty list.


val testList2 = mutableListOf(mutableListOf<String>())

// using
public fun <T> mutableListOf(vararg elements: T): MutableList<T> =
    if (elements.size == 0) ArrayList() else ArrayList(ArrayAsCollection(elements, isVarargs = true))
        

Here, you can define an empty mutable list by these codes.

val testList: MutableList<MutableList<String>> = mutableListOf()

// or
val testList = mutableListOf<MutableList<String>>()

// using
public inline fun <T> mutableListOf(): MutableList<T> = ArrayList()

CodePudding user response:

Whatever you pass to the mutableListOf function is the initial contents of the list it returns. Since you have nested a call of mutableListOf() inside the outer call to mutableListOf(), you are creating your list with an initial value of another MutableList.

If you want your list to start empty, don’t put anything inside the () when you call mutableListOf().

If you construct your list this way, you need to specify the type of the list, since it won’t have an argument to infer the type from.

Either

val testList2 = mutableListOf<MutableList<String>>()

or

val testList2: MutableList<MutableList<String>> = mutableListOf()
  • Related