3 - List - Listof
3 - List - Listof
Kotlin
In this example, we create a new list called numbers using the listOf() function.
The list contains five elements: the integers 1 through 5. Since the list is
immutable, we cannot modify its contents once it has been created.
Kotlin
In this example, we use indexing to access the first and last elements of the
numbers list. Note that indexing is 0-based in Kotlin, so the first element has
an index of 0 and the last element has an index of numbers.size – 1.
We can also iterate over the list using a for loop, like this:
Kotlin
In this example, we use a for loop to iterate over the numbers list and print
each element to the console.
Here are some advantages and disadvantages of using the listOf() function in
Kotlin:
Advantages:
A list is a generic ordered collection of elements. Kotlin has two types of lists,
immutable lists (cannot be modified) and mutable lists (can be modified).
Read-only lists are created with listOf() whose elements can not be modified
and mutable lists created with mutableListOf() method where we alter or
modify the elements of the list.
Kotlin program of list contains Integers –
Java
Output:
3
1
3
Java
Output:
Each element of a list has an index. The first element has an index of zero (0)
and the last Element has index
len – 1, where ‘len’ is the length of the list.
Java
Output:
1
6
The first index of number is 0
The last index of number is 6
The last index of the list is 8
Java
Output:
1
10
Java
// method 1
for (name in names) {
print("$name, ")
}
println()
// method 2
for (i in 0 until names.size) {
print("${names[i]} ")
}
println()
// method 3
names.forEachIndexed({i, j -> println("names[$i] = $j")})
// method 4
val it: ListIterator<String> = names.listIterator()
while (it.hasNext()) {
val i = it.next()
print("$i ")
}
println()
}
Output:
Explanation:
The for loop traverses the list. In each cycle, the variable ‘name’ points to the
next element in the list.
print("${names[i]} ")
}
This method uses the size of the list. The until keyword creates a range of the
list indexes.
With the forEachIndexed() method, we loop over the list having index and
value available in each iteration.
while (it.hasNext()) {
val i = it.next()
print("$i ")
}
Output:
[0, 1, 2, 3, 4, 5, 6, 7, 8]
[8, 7, 6, 5, 4, 3, 2, 1, 0]
Explanation:
Java
fun main(args: Array<String>)
{
val list = listOf(8, 4, 7, 1, 2, 3, 0, 5, 6 )
if (res)
println("The list contains 0")
else
println("The list does not contain 0")
if (result)
println("The list contains 3 and -1")
else
println("The list does not contain 3 and -1")
}
Output:
Explanation:
Checks whether the list contains 0 or not and returns true or false (her true)
that is stored in res.