Kotlin集合类型之Map、MutableMap
Map是一个接口和通用的元素集合。 Map以键和值对的形式保存数据。 映射的键是唯一的,每个键只保留一个值。 键和值可以是不同类型。 也被分为可变的和不可变的,即Map与MutableMap.
Map
它是不可变的,它的大小固定,方法支持只读访问。要使用Map接口,需要使用mapOf()或mapOf <k,v>()函数声明。
声明和创建Map集合
声明和创建Map有很多方式,下面一一介绍:
mapOf()声明一个空的map:
返回一个只读的空的map
源码:
/**
* Returns an empty read-only map.
*
* The returned map is serializable (JVM).
* @sample samples.collections.Maps.Instantiation.emptyReadOnlyMap
*/
@kotlin.internal.InlineOnly
public inline fun <K, V> mapOf(): Map<K, V> = emptyMap()
声明:
val first = mapOf<String, String>()
mapOf()声明非空Map:
返回不可变的Map集合。接收多个key-value对,这些key-value对将作为Map的元素。
源码:
/**
* Returns a new read-only map with the specified contents, given as a list of pairs
* where the first value is the key and the second is the value.
*
* If multiple pairs have the same key, the resulting map will contain the value from the last of those pairs.
*
* Entries of the map are iterated in the order they were specified.
*
* The returned map is serializable (JVM).
*
* @sample samples.collections.Maps.Instantiation.mapFromPairs
*/
public fun <K, V> mapOf(vararg pairs: Pair<K, V>): Map<K, V> =
if (pairs.size > 0) pairs.toMap(LinkedHashMap(mapCapacity(pairs.size))) else emptyMap()
声明:
val name = mapOf<String, String>("name" to "alfred", "sex" to "man", "age" to &#