We can get the size of an ArrayList using the .size property:
val ourArray = mutableListOf(50, 40, 30)
// Printing the size:
println(ourArray.size) // Output: 3
// Changing the ArrayList:
ourArray.removeAt(2)
// Printing the new size:
println(ourArray.size) // Output: 2
Using the size
We can use the size to access items from the end of an ArrayList.
Because ArrayLists are 0-indexed, the index of the last item is size - 1:
val ourArray = mutableListOf(50, 40, 30)
val size = ourArray.size
// Printing the last item:
println(ourArray[size - 1]) // Output: 30
// Printing the second to last item:
println(ourArray[size - 2]) // Output: 40
Assignment
Follow the Coding Tutorial and let's play with some arrays.
Hint
Look at the examples above if you get stuck.
Free plan: 30 tutor messages. PRO is unlimited.
Saved
Ctrl + Enter to check
