Kotlin MutableList (mutableListOf())Kotlin MutableList is an interface and generic collection of elements. MutableList interface is mutable in nature. It inherits form Collection<T> class. The methods of MutableList interface supports both read and write functionalities. Once the elements in MutableList have declared, it can be added more elements in it or removed, so it has no fixed size length. To use the MutableList interface we use its function called mutableListOf() or mutableListOf<E>(). The elements of MutableList follow the sequence of insertion order and contains index number same as array. MutableList Interface DeclarationFunction of Kotlin MutableListThere are several methods are available in MutableList interface. Some methods of MutableList interface are mention below.
Kotlin MutableList Example 1Let's see an example of MutableList using mutableListOf() function and traverse its elements. Output: Ajay Vijay Prakash Vijay Ajay Vijay Prakash Vijay Kotlin MutableList Example 2The function mutableListOf() of MutableList interface provides facilities to add elements after its declaration. MutableList can also be declared as empty and added elements later but in this situation we need to define its generic type. For example: Output: Ajay Vijay Prakash Vijay Ajeet Amit Akash Kotlin MutableList Example 3For more specific we can provide the generic types of MutableList interface such as mutableListOf<Int>(), mutableListOf<String>(), mutableListOf<Any>(). The mutableListOf<Int>() takes only integer value, mutableListOf<String>() takes only String value and mutableListOf<Any>() takes different data types value at the same time. Let's see the example. Output: .....print Int type..... 5 7 15 10 .....print String type..... Ajeet Ashu Mohan .....print Any type..... Sunil 2 5 Raj Kotlin MutableList Example 4Let's see the use of different function of MutableList interface using mutableListOf<T>() function. Output: .....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]
Next TopicKotlin ArrayList
|