F
F
foonfyrick2021-03-25 11:56:24
Kotlin
foonfyrick, 2021-03-25 11:56:24

SetOf listOf mapOf entries are similar? Line 1 -> setOf(this[0])?

1) Question:
val list:List = listOf()
In the creation implementation, I saw the lines:

public fun listOf(vararg elements: T): List = if (elements.size > 0) elements.asList() else emptyList()
if go further, then:
public actual fun Array.asList(): List {
return ArraysUtilJVM.asList(this)
}
and so in the end I reach this implementation:
public static List asList(T... a) {
return new ArrayList<> (a);
}
That is, it turns out that these 2 records are similar? :
val list:List = listOf() and val list:List = ArrayList() are these entries similar?

Are maps and sets created in the same way also similar to the following entries? :
val map:Map = mapOf() and val map:Map = LinkedHashMap()
val set:Set = setOf() = val set:Set =LinkedHashSet()

That is, I can say that listOf creates an ArrayList of the List interface, mapOf creates a LinkedHashMap of the interface Map and setOf creates a LinkedHashSet of the Set interface?

2) Question:

Going into the implementation of setOf there is a line: if (elements.size > 0) elements.toSet() and going into toSet() there is such an implementation:
public fun Array.toSet(): Set {
return when (size) {
0 -> emptySet()
1 -> setOf(this[0])
else -> toCollection(LinkedHashSet(mapCapacity(size)))
}
}
What does line 1 -> setOf(this[0]) mean? That is, if val set = setOf(1), then emptySet() will be created inside setOf or what?
And only if the size of setOf is greater than 1, then only LinkedHashSet will be created?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vladimir Chetverikov, 2021-04-10
@foonfyrick

1. In the current implementation, this is how it is - listOf() creates an ArrayList. Other methods for creating collection instances are similar.
link to the documentation https://kotlinlang.ru/docs/reference/collections.html :
At the moment, the listOf method is implemented using ArrayList, but it is possible that in the future other types of collections that are more memory efficient due to its immutability.
2. Line 1 -> setOf(this[0]) means that the function
public fun setOf(element: T): Set = java.util.Collections.singleton(element)
from the kotlin.collections package will be called to create it.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question