Arrays
A data structure that holds a fixed number of values of the same type or its subtypes. The most common type of array in Kotlin is the object-type array, represented by the Array
class.
Arrays | Collections |
Arrays can be both be read & over-written. | Collections are read-only, giving us more control |
Fixed Size, hence difficult to add & remove elements | Easier to add or remove elements from collections |
Comparison of Array is done using special functions | Comparison of Array can be done using the equality = operator |
Hence, low-level requirements are typically fulfilled by arrays, and depending on the requirements, collections may also satisfy the need.
Creating Arrays :
An array is created using the arrayOf()
function.
val simpleArray = arrayOf<Int>(1, 2, 3)
val arr = arrayOf("A","B","C")
val details = arrayOf<Any>("Mercedez",2.0,"260hp")
Accessing Elements of Arrays :
Elements of an array can be accessed with the indexed access operator []
or by the get()
method
arr.get(0) //takes index as parameter
arr[1] //takes index as parameter
arr.set(0,"Z") //used to change the element at an index
Convert arrays to collection :
Arrays can be converted to Collections using the toList()
, toSet()
& toMap()
method.
Size of an Array :
arr.size //returns size of arr
ArrayList
ArrayList is used to create dynamic arrays, i.e. the size of an ArrayList can be increased or decreased.
Creating ArrayList :
var age = arrayListOf<Int>(1,2,3) //can add elements later too..
var age = ArrayList<Int>() //can't specify elements during declaration
//can add elements later
Adding or Removing elements from an ArrayList :
age.add(10) //adds element at the end of the list.
age.add(0,10) //adds element at the 0th index of list.
age.remove(10) //remove element of list.
age.removeAt(0) //removes element at 0th index of the list.
Accessing Elements of ArrayList :
Elements of an ArrayList can be accessed with the indexed access operator []
or by the get()
method
age.get(0) //takes index as parameter
age[1] //takes index as parameter
age.set(0,"Z") //used to change the element at an index
Size of an Array :
arr.size //returns size of arr
Set
Set is a collection that stores unique elements; their order is generally undefined.
val theSet = setOf("one", "two", "three", "four")
val mySet = setOf(1,2,3,1)
mySet.size //returns 3
mySet.last //returns the last element : 3
Map
Kotlin map is a collection of key/value pairs, where each key is unique, and can only be associated with one value. The same value can be associated with multiple keys though. We can declare the keys and values to be any type; there are no restrictions.
val numbersMap = mapOf<String,Int>("key1" to 1, "key2" to 2, "key3" to 3, "key4" to 1)
println("All keys: ${numbersMap.keys}")
println("All values: ${numbersMap.values}")
Creating Mutable Maps :
Hence, the content of the map can be altered.
val map = mutableMapOf<Any,Any>(1 to "abc", 2 to "rahul")
map[0] = "raman"