Left Index

Kotlin arrayListOf()

We can create ArrayList object using constructor of ArrayList or arrayListOf() as shown in below code snippet.

Example:
package com.theitbulls.kotlinex

import java.util.ArrayList

fun main(args: Array<String>) {
	// create ArrayList object using empty constructor
	// creating arrayList of type String
	var arrayList1 = arrayListOf<String>()
	arrayList1.add("John")
	arrayList1.add("Marry")
	printList(arrayList1)
	
	// creating arrayList with argument
	var arrayList2 = arrayListOf("Vijay", "Karan")
	arrayList2.add("John")
	arrayList2.add("Jony")
	printList(arrayList2)
	
	// creating arrayList of type Int
	var arrayList3 = arrayListOf<Int>()
	arrayList3.add(23);
	arrayList3.add(11);
	arrayList3.add(99);
	printList(arrayList3)
}

fun <T> printList(arrList: ArrayList<T>) {
	for(item in arrList) {
		when(item) {
			is String -> println(item)
			is Int -> println(item)
		}
	}
	println()
}
Output:
John
Marry

Vijay
Karan
John
Jony

23
11
99


Mixed ArrayList in Kotlin

Let's have an example of ArrayList with mixed data types.

Example:
package com.theitbulls.kotlinex

import java.util.ArrayList

fun main(args: Array<String>) {
	// creating arrayList with argument
	var arrayList2 = arrayListOf<Any>(23, "Vijay", 21, "Karan")
	printList(arrayList2)
}

fun <T> printList(arrList: ArrayList<T>) {
	for(item in arrList) {
		when(item) {
			is String -> println(item)
			is Int -> println(item)
		}
	}
	println()
}
Output:
23
Vijay
21
Karan