Kotlin HashMap 类2024 年 8 月 29 日 | 4 分钟阅读 Kotlin HashMap 是基于 MutableMap 接口的集合类。 Kotlin HashMap 类使用哈希表实现 MutableMap 接口。它以键值对的形式存储数据。它表示为 HashMap<key, value> 或 HashMap<K, V>。 HashMap 类的实现不保证集合的键、值和条目的数据顺序。 Kotlin HashMap 类的构造函数
Kotlin HashMap 类的函数
Kotlin HashMap 示例 1 - 空 HashMap让我们创建一个简单的 HashMap 类示例,定义一个 <Int, String> 的空 HashMap,并在以后添加元素。要打印 HashMap 的值,我们将使用HashMap[key]或HashMap.get(key)。 输出 .....traversing hashmap....... Element at key 1 = Ajay Element at key 2 = Ajay Element at key 3 = Vijay Element at key 4 = Praveen Kotlin HashMap 示例 2 - HashMap 初始容量HashMap 也可以使用其初始容量进行初始化。可以通过添加和替换其元素来更改容量。 输出 .....traversing hashmap....... Element at key name = Ajay Element at key department = Software Development Element at key city = Delhi .....hashMap.size....... 3 .....hashMap.size after adding hobby....... 4 .....traversing hashmap....... Element at key name = Ajay Element at key department = Software Development Element at key city = Delhi Element at key hobby = Travelling Kotlin HashMap 示例 3 - remove() 和 put()函数remove()用于将指定键的现有值替换为指定值。 put() 函数在指定键处添加一个新值并替换旧值。如果put()函数没有找到任何指定的键,它会在指定的键处放入一个新值。 输出 .....traversing hashmap....... Element at key 1 = Ajay Element at key 2 = Rohan Element at key 3 = Vijay Element at key 4 = Prakash .....hashMap.replace(3,"Ashu")...hashMap.put(2,"Raj").... Element at key 1 = Ajay Element at key 2 = Raj Element at key 3 = Ashu Element at key 4 = Prakash Kotlin HashMap 示例 4 - containsKey(key) 和 containsValue(value)如果 HashMap 中存在指定的键,函数containsKey()返回 true,如果不存在这样的键,则返回 false。 函数containsValue()用于检查 HashMap 中是否存在指定的值。如果 HashMap 中存在该值,它将返回 true,否则返回 false。 输出 .....traversing hashmap....... Element at key 1 = Ajay Element at key 2 = Rohan Element at key 3 = Vijay Element at key 4 = Prakash .....hashMap.containsKey(3)....... true .....hashMap.containsValue("Rohan")....... true Kotlin HashMap 示例 5 - clear()clear()函数用于清除 HashMap 中的所有数据。 输出 .....traversing hashmap....... Element at key 1 = Ajay Element at key 2 = Rohan Element at key 3 = Vijay Element at key 4 = Prakash .....hashMap.clear()....... .....print hashMap after clear()....... {} |
我们请求您订阅我们的新闻通讯以获取最新更新。