arrays-kotlin

Arrays in Kotlin

Array is a collection of similar type of elements that have contiguous memory location. Kotlin array is an object the contains elements of similar data type. It is a data structure where we store similar elements.

It is also known as static data structure because size of an array must be specified at the time of its declaration. The length of an array is established when the array is created

Array in kotlin is index based, first element of the array is stored at 0 index.

Kotlin Array can be created using below functions

  • arrayOf()
  • intArrayOf()
  • charArrayOf()
  • booleanArrayOf()
  • longArrayOf()
  • shortArrayOf()
  • byteArrayOf()

Types of Array:

  • One-dimensional array(1-D: it's a single array that holds multiple values of the same type.
  • Two-dimensional array(2-D): it's an array containing multiple arrays within it, where all of these multiple array holding values of a same type.

Kotlin array declaration - using arrayOf() function


var myArray1 = arrayOf(1,10,4,6,15)  
var myArray2 = arrayOf(1,10,4,6,15)  
val myArray3 = arrayOf("Ajay","Prakesh","Michel","John","Sumit")  
var myArray4= arrayOf(1,10,4, "Ajay","Prakesh")   

Kotlin array declaration - using intArrayOf() function


var myArray5: IntArray = intArrayOf(5,10,20,12,15)    

kotlin array constructor :

Array constructor is declared with specified size and init function. The init function is used to returns the elements of array with their index.


Array(size: Int, init: (Int) -> T) 

Kotlin Empty Array :

An empty array does not contains any element in it, while initializing we may cerate empty array. The size of the empty array is zero, if we try to access an element in empty array then Kotlin throws java.lang.ArrayIndexOutOfBoundsException as there is no element is present.

You Can create kotlin empty array in following ways:


var arr = Array (0, { i -> "" })
var arr2 = array()

If you create empty array using above ways, koltin will not let you to add element but if you want to addelement then you should initialize the arry with some size. below array accepts amximum 5 element into array.


var arrayString=Array(5){null}
var nullArray= arrayOfNulls(5)

Add a element to kotlin array

if you want to add elements to an array in kotlin, you can use the index operator to assign the value. Be aware that index starts with zero (0).


var arr2 = array()
arr2[0] = "chercher tech"

When you assign a value using the index, it just replaces the existing value at the given index, it will not add a new index to the array.

Access values in Array :

You can access the array elements using the index [] operator,


val days = arrayOf("Mon", "Tue", "Wed", "Th", "Fri", "Sat", "Sun")
// Return the value of the first element in the array.
println(days[0]) // prints mon

get() and set() in kotlin arrays :

Kotlin has set() and get() functions that can direct modify and fetch the particular element of array respectively. you can use get and set instead of using the index operator [ ].


val array1 = arrayOf(1,2,3,4)  
val array2 = arrayOf(11,12,13,14)  
array1.set(0,5)  
array1[2] = 6  
array2.set(2,10) 
array2[3] = 8

Exceptions in kotlin

take() function in kotlin array :

You can use the take() function to retrieve given number of element from array from the beginning of array. You have to specify the number of elements you want to take from the array


val allColours = arrayOf("red", "blue", "green")
println(allColours.take(2))

Will give you first two elements ["red", "blue"]

sliceArray in kotlin :

slicearray() function returns an array containing elements at indices in the specified indices range of the kotlin array. Do remember that you have to provide range to slice the array in kotlin.

Kotlin array slice example


val allColours = arrayOf("red", "blue", "green", "White", "black")
println(allColours.slicearray(0..2))

kotlin array contains() :

contains() functions returns true if element is found in the array otherwise false.


val allColours = arrayOf("red", "blue", "green", "White", "black")
println(allColours.contains("grey"))
println(allColours.contains("RED"))
println(allColours.contains("red"))

kotlin array size

size property in kotlin array return the number of elements present in the array. Sometimes people may ask for length of the array which is also denotes the size of the array.


val allColours = arrayOf("red", "blue", "green", "White", "black")
println(allColours .size)

equals() function in arrays

equals() function compares the given object with the receiver (on the object we have called the equals()). If both arrays are same then equals() function returns true otherwise false.


val allColours = arrayOf("red", "blue", "green", "White", "black")
val fewColours = arrayOf("red", "blue")
println(allColours.equals(fewColors))

lastIndex in Array

lastIndex property in arrays returns the last valid index, if you try to access any index after the last index you might face java.lang.ArrayIndexOutOfBoundsException.

lastIndex is always equal to array.size -1


val allColours = arrayOf("red", "blue", "green", "White", "black")
println(allColours.lastIndex)

convert array to list in kotlin

Kotlin standard library has toList() function which will convert the given array into a list Immutable array


val allColours = arrayOf("red", "blue", "green", "White", "black")
allColours .toList()
Mutable Array:
allColours .toMutableList()

asList() in arrays

asList() function returns a List that wraps the original array.


val allColours = arrayOf("red", "blue", "green", "White", "black")
allColours .asList()

arrays as paramater in kotlin

You can write a function which accepts a array as parameter with type, for example our main function() accepts array of Strings.

To call function which accepts Array we must pass the arrays as argument in the function call.


fun sampleFunction(args : Array<String>){
for(arg in args){
println(arg)
}
sampleFunction(arrayOf("karthiq", "chercher tech"))

Convert kotlin byte array to string

You can use toString(charset) to convert a byte array to string using the given encoding.


val bytes = byteArrayOf(33, 87, 15, 5)
bytes.toString(Charset.defaultCharset())

Classes in kotlin

Convert kotlin byte array to hex string

To convert byte array to hex value, we loop through each byte in the array and use String's format() function.

We use %02X to print two places (02) of Hexadecimal (X) value and store it in the string st.


fun main(args: Array) {
    val bytes = byteArrayOf(33, 87, 15, 5)
    for (b in bytes) {
        val st = String.format("%02X", b)
        print(st)
    }
}

copy kotlin array

copyOf() function returns a new array which is a copy of the original array.


val array = arrayOf("apples", "oranges", "limes")
val arrayCopy = array.copyOf()

resize a array with copyOf *

copyOf() function returns a new array which is a copy of the original array, resized to the given size. The copy is either truncated or padded at the end with zero values based on the new size.

  • If newSize is less than the size of the original array, the copy array is truncated to the newSize.
  • If newSize is greater than the size of the original array, the extra elements in the copy array are filled with zero values.

val array = intArrayOf(1, 2, 3)
val arrayCopyPadded = array.copyOf(5)
println(arrayCopyPadded.contentToString()) // [1, 2, 3, 0, 0]
val arrayCopyTruncated = array.copyOf(2)
println(arrayCopyTruncated.contentToString()) // [1, 2]

The zero at the end is not commaon for all the array types, it differs based on the type of array, for example fasle for Boolean array.

kotlin array concatenation

You can combine two arrays using the + operator in kotlin


var array1 = intArrayOf(1,2,3)
var array2 = intArrayOf(4,5,6)
var array3 = array1 + array2

Union in arrays

union() method can take a collection as parameters. It can merge two arrays but it returns a Set. So, we will have unique data but it will merge two arrays.


var array1 = intArrayOf(1,2,3)
var array2 = intArrayOf(4,5,6)
var array3 = array1.union(array2.asList())
println(array3)

Convert the char array to string

You can use joinToString() function to combine all the element with particular character. If you donot want to use any symbol then use empty string.

val result: String = chars.joinToString("");

You can use the String constuctor to form a string using the Char Array.


val chars = charArrayOf('A', 'B', 'C');
val result1: String = String(chars);

ENUMS in Kotlin

drop() in kotlin

drop() function returns a array containing all elements except first n-elements.


val chars = ('a'..'z').toList()
println(chars.drop(23)) // [x, y, z]
println(chars.dropLast(23)) // [a, b, c]
println(chars.dropWhile { it < 'x' }) // [x, y, z]
println(chars.dropLastWhile { it > 'c' }) // [a, b, c]

array to varags

we can use the spread operator that basically spreads the elements to make arrays compatible with varargs.

If I have a function header like:


fun addAttributes(vararg attributes: String) {
  ...
}
addAttributes(*atts)

kotlin array foreach

forEach can be used to repeat a set of statement for each element in an iterable (could be list, set, array).


var daysOfWeek = listOf("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday")
    daysOfWeek.forEach{
        println(it)
   }

kotlin array min

min() function returns the smallest element or null if there are no elements.


var array1 = intArrayOf(1,2,3)
println(array1.min())

arrayOfNulls()

arrayOfNulls() function returns an array of objects of the given type with the given size, initialized with null values.


val arrayOfNulls = kotlin.arrayOfNulls(9)
println (arrayOfNulls)

The result would be: [null, null, null, null, null, null, null, null, null]

reversedArray() in Kotlin

reversedArray() reverses the array elements and returns new array.


var array1 = intArrayOf(1,2,3)
println(array1.reversedArray())

kotlin array sort

sort() function sorts the array in-place according to the natural order of its elements.


var array1 = intArrayOf(1,2,3)
println(array1.sort())

kotlin array sum

sum() function returns the sum of all elements in the array. sum() function is only applicable on Number datatype


var array1 = intArrayOf(1,2,3)
println(array1.sum())

kotlin shuffle array

shuffle() function randomly shuffles elements in the array.


var array1 = intArrayOf(1,2,3)
println(array1.shuffle())

Access/Visibility Modifiers

kotlin iterate array with index

You can use the withIndex library function to the element and index of an element.


var array = intArrayOf(1,2,3)
for ((index, value) in array.withIndex()) {
    println("the element at $index is $value")
}

kotlin return array

You can return an array in a function just like any other value in kotlin.


fun returnArrayFunction():Array{
	println("this function returns array")
	return arrayOf("chercher tech", "karthiq", "google")
}

kotlin array split using Chunked

chunked() methods help you to form multiple array by splitting the big array based on the given size. For example if you have 6 elements in original array and if you use chunked(3), then it creates two arrays with three elements each.


var array1 = intArrayOf(1,2,3,4,5,6)
println(array1.chunked(3))

kotlin array find

find() function returns the first element matching the given predicate/condition, or null if no such element was found.

aaaaaaaaaaaaa
Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions

Recent Addition

new tutorial Selenium Online Training : Our next online training course for Selenium with Java starts from 17th December 2018.

You can attend first 3 classes for free, the total course fee is INR 10,000

The course time would be 8.00 PM(IST) for the first three classes

If you are interested to learn, then you can join the course by sending email to chercher.tech@gmail.com

or Register below


 
Join My Facebook Group
Join Group