6.3 Kotlin集合类型之Map、MutableMap

Kotlin集合类型之Map、MutableMapMap声明和创建Map集合Map常用函数Kotlin MutableMap声明和创建MutableMapMutableMap常用函数HashMap、LinkedHashMap、TreeMapMap是一个接口和通用的元素集合。 Map以键和值对的形式保存数据。 映射的键是唯一的,每个键只保留一个值。 键和值可以是不同类型。 也被分为可变的和不可变的,即Map与MutableMap.Map它是不可变的,它的大小固定,方法支持只读访问。要使用Map接口,需要
摘要由CSDN通过智能技术生成


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 &#
  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Alfred Gao

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值