android kotlin hashmap initialization

MainActivity.kt
package com.example.espl.hashmapkotlinapp
import android.os.Build
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.util.Log

class MainActivity : AppCompatActivity() {
        // Different ways for hashmap initialization in Kotlin Android
        //    fun <K, V> hashMapOf(): HashMap<K, V>
        //    Returns an empty new HashMap.
        //    Method hashMapOf() in Kotlin
        val hashMap: HashMap<Int,String> = hashMapOf()

        //    Returns a new HashMap with the specified contents, given as a list of pairs where the  first component is the key and the second is the value.
        //    fun <K, V> hashMapOf(vararg pairs: Pair<K, V>): HashMap<K, V>
        // kotlin init hashmap with values
     val specifiedContentsMap: HashMap<Int, String> = hashMapOf(1 to "x", 2 to "y", -1 to "zz")

        //define empty hash map
        val initEmptyHashMap:HashMap<Int,String> = HashMap()

        //    initialize with its initial capacity of 3
        val initialCapacityHashMap:HashMap<Int,String> = HashMap(3)

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

        // kotlin hashmap put example - add item
        hashMap.put(1,"Value1")
        hashMap.put(2,"Value2")
        hashMap.put(3,"Value3")
        hashMap.put(4,"Value4")
        hashMap.put(5,"Value5")

        // kotlin hashmap add item
        initEmptyHashMap.put(1,"Value1")
        initEmptyHashMap.put(2,"Value2")
        initEmptyHashMap.put(3,"Value3")

        initialCapacityHashMap.put(1,"Value1")
        initialCapacityHashMap.put(2,"Value2")
        initialCapacityHashMap.put(3,"Value3")
        initialCapacityHashMap.put(4,"Value4")

        //print hash map in Log
        Log.e("hashmap","::"+hashMap)
        Log.e("specifiedContentsMap","::"+specifiedContentsMap)
        Log.e("initEmptyHashMap","::"+initEmptyHashMap)
        Log.e("initialCapacityHashMap","::"+initialCapacityHashMap)
    }
}

Output:
com.example.espl.hashmapkotlinapp E/hashmap: ::{4=Value4, 1=Value1, 5=Value5, 3=Value3, 2=Value2}
com.example.espl.hashmapkotlinapp E/specifiedContentsMap: ::{-1=zz, 1=x, 2=y}
com.example.espl.hashmapkotlinapp E/initEmptyHashMap: ::{1=Value1, 3=Value3, 2=Value2}
com.example.espl.hashmapkotlinapp E/initialCapacityHashMap: ::{4=Value4, 1=Value1, 3=Value3, 2=Value2}

No comments:

Post a Comment

Popular Posts