Tuesday 21 April 2020

Kotlin : Collections Mutable & Immutable with List & Array List (Post 16)

Hi ,

Let's take a look , how collections work in Kotlin . There are basically 2 types of Collections :

Mutable & Immutable

Immutable :  Read Only Operations , Fixed Size 

  • Immutable List : listOf
  • Immutable Map : mapOf
  • Immutable Set: setOf
Mutable :  Read  & Write Operations , Not Fixed Size 

  • Mutable List :  ArrayList , ArrayListOf , mutableListOf
  • Mutable Map : HashMap , HashMapOf, mutableMapOf
  • Mutable Set:    HashSetOf , mutableSetOf

     
Here I am sharing a basic example of List & ArrayList , to understand how can we use it :

override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        //immutable , fixed size , Read only operation
        var myList  =  listOf<String>("Android" , "iOS" , "Flutter")
        for(element in myList){
        println(element)
        }

        //mutable ,not fixed in size ,Read & Write Operations
        var mutableList1  =  arrayListOf<String>()
        var mutableList2  =  ArrayList<String>()
        var mutableList  =  mutableListOf<String>()
        mutableList.add("android") //0
        mutableList.add("iOS") //1
        mutableList.add("flutter") //2

        //remove
        mutableList.remove("iOS") //removing @ 1 index
        mutableList.add("React Native") //adding @ 1 index
        for(element in mutableList){
            println(element)
        }
    }

Output : 
Android
iOS
Flutter

android
React Native
flutter

Explaination: 
Here we can see that with immutable list , we can only READ the elements  , but with mutable list I have removed one element from index 1 and then add another element at index 1 .
Also I have shared all the types of mutable list which we can use it in our code  , let's take a look what are the types of these array lists :

 var mutableList1: ArrayList<String> =  arrayListOf<String>()
 var mutableList2: ArrayList<String> =  ArrayList<String>()
 var mutableList: MutableList<String> =  mutableListOf<String>()

Here one thing is noticable that  MutableList<String> , is also implemented by ArrayList<String>

So that was very basic explanation of List / ArrayList , which will help to understand the functionality. In next post I will share for Map and Set , till then Happy Coding 😀😀


No comments:

Post a Comment

Advanced Kotlin Coroutines : Introduction

 Hi,  Today I am unwraping the topic in Kotin world i.e. Coroutine . If you want to get started with Kotlin coroutine and ease your daily de...