Kotlin MutableList (mutableListOf())2024 年 8 月 29 日 | 4 分钟阅读 Kotlin MutableList 是一个接口和元素的泛型集合。 MutableList 接口本质上是可变的。 它继承自 Collection<T> 类。 MutableList 接口的方法支持读取和写入功能。 一旦在 MutableList 中声明了元素,就可以在其中添加或删除更多元素,因此它没有固定的大小长度。 要使用 MutableList 接口,我们使用它的函数,称为 mutableListOf() 或 mutableListOf<E>()。 MutableList 的元素遵循插入顺序,并包含与数组相同的索引号。 MutableList 接口声明Kotlin MutableList 的函数MutableList 接口中提供了几种方法。 下面提到了一些 MutableList 接口的方法。
Kotlin MutableList 示例 1让我们看一个使用 mutableListOf() 函数的 MutableList 示例,并遍历它的元素。 输出 Ajay Vijay Prakash Vijay Ajay Vijay Prakash Vijay Kotlin MutableList 示例 2MutableList 接口的函数 mutableListOf() 提供了在其声明后添加元素的工具。 MutableList 也可以声明为空,并在以后添加元素,但在这种情况下,我们需要定义其泛型类型。 例如 输出 Ajay Vijay Prakash Vijay Ajeet Amit Akash Kotlin MutableList 示例 3对于更具体的情况,我们可以提供 MutableList 接口的泛型类型,例如 mutableListOf<Int>(), mutableListOf<String>(), mutableListOf<Any>()。 mutableListOf<Int>() 只接受整数值, mutableListOf<String>() 只接受字符串值,而 mutableListOf<Any>() 同时接受不同的数据类型值。 让我们看一个例子。 输出 .....print Int type..... 5 7 15 10 .....print String type..... Ajeet Ashu Mohan .....print Any type..... Sunil 2 5 Raj Kotlin MutableList 示例 4让我们看看使用 mutableListOf<T>() 函数的 MutableList 接口的不同函数的用法。 输出 .....mutableList..... Ajay Vijay Prakash .....mutableList[2]..... Prakash ......mutableList.add(2,"Rohan")...... Ajay Vijay Rohan Prakash .....mutableList.add("Ashu")...... Ajay Vijay Rohan Prakash Ashu ... mutableList.addAll(1,mutableList3).... Ajay Dharmesh Umesh Vijay Rohan Prakash Ashu ...mutableList.addAll(mutableList2).... Ajay Dharmesh Umesh Vijay Rohan Prakash Ashu Rohan Raj ...mutableList.remove("Vijay").... Ajay Dharmesh Umesh Rohan Prakash Ashu Rohan Raj ....mutableList.removeAt(2).... Ajay Dharmesh Rohan Prakash Ashu Rohan Raj .... mutableList.removeAll(mutableList2).... Ajay Dharmesh Prakash Ashu ....mutableList.set(2,"Ashok").... Ajay Dharmesh Ashok Ashu .... mutableList.retainAll(mutableList4).... Ajay Dharmesh Ashu .... mutableList2.clear().... .... mutableList2 after mutableList2.clear().... [] ....mutableList.subList(1,2).... [Dharmesh] 下一个主题Kotlin ArrayList |
我们请求您订阅我们的新闻通讯以获取最新更新。