List interfaces

The list interface is the last interface in the hierarchy related to the immutable collection. This is probably the most used collection in Kotlin.

The list interface inherits all functions from its parents interfaces and provides its own functions as well:

The list interface is an ordered collection, so we can access its elements using its index. Let's have a look at the functions it provides:

  • get(index): This function returns an element at a specific index
  • indexOf(element): This function returns the index of a specific element
  • lastIndexOf(): This function returns the last value of the list
  • subList(from, to): This function returns a subset from the list

At the beginning of this section, we created different types of lists using the listOf function:

val listOfInteger = listOf(1,2,3,4,5) 

All of these lists are basically exposed by the List interface. The complete syntax of the list interface is as follows:

val listOfInteger:List<Int> = listOf(1,2,3,4,5)

fun listInterfaceFunctions(){

val listOfInteger:List<Int> = listOf(1,2,3,4,5)
var index = 0
println("At index $index element ${listOfInteger.get(index)}")

var element = 1
println("List contains $element at index ${listOfInteger.indexOf(element)}")
println("List contains $element at last index ${listOfInteger.lastIndexOf(element)}")

println("Subset of list")

val subsetOfList = listOfInteger.subList(0,3)
for (value in subsetOfList){
println(value)
}
}

We have already discussed most of these functions in previous sections. The only new function is the subList function, which returns the subset of a list between specified indexes. This function takes two integer parameters. The first parameter represents the starting index and the second parameter represents the last index that is not included:

val subsetOfList = listOfInteger.subList(0,3)

The subList() function will return the first three elements of the list. The List interface provides two special types of iterators, which will be discussed in the Iterators section. 

..................Content has been hidden....................

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