Mutable collection interfaces

The mutableCollection interface extends two rich interfaces—the mutable iterable interface and the collection interface. It provides its own functions to add or remove elements. First, create a list of a mutable collection using the mutableCollection interface. Take a look at the following example:

val mutableCollectionList : MutableCollection <Int> = mutableListOf(1,2,3,4,5)

Take a look at the following diagram of the MutableCollection interface, which inherits both the MutableIterator interface and the Collection interface:

The MutableCollection interface provides the following functions:

  • Add(): This function inserts an element at the end of list. It returns true if the operation is successful, otherwise it returns false:
var item = 6
var result = mutableCollectionList.add(item)
println("Item $item is added in collection = $result")

  • Remove(): This function removes the first occurrence of the specified element. It returns true if the operation is successful, otherwise it returns false:
item = 7
mutableCollectionList.remove(item)
  • retainAll(): This function takes a list as a parameter. It removes all elements from the main list, except the elements in the list parameter. It returns true if the operation is successful, otherwise it returns false:
val retain = listOf(2,4,6,8)
mutableCollectionList.retainAll(retain)
  • addAll(): This function inserts another list at the end of main list. It returns true if the operation is successful, otherwise it returns false. Create a list called miniCollection and insert it in the main list as follows:
var miniCollection = listOf(9,8,7)
result = mutableCollectionList.addAll(miniCollection)
println("Mini collection is added in collection = $result")
  • clear(): This function removes all elements from the list:
mutableCollectionList.clear()
if (mutableCollectionList.size == 0 ) {
println("List is clear, add mini collection")
mutableCollectionList.addAll(miniCollection)
}
println(mutableCollectionList)
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.125.51