Home > Software engineering >  Kotlin: save null value in ArrayList?
Kotlin: save null value in ArrayList?

Time:06-04

I have created an ArrayList of nullable types, but when I try to add a null value to the list the null value doesn't get added. eg.

var intArray: ArrayList<Int?>? = null
intArray = ArrayList()

intArray.add(0)
intArray.add(null)
intArray.add(2)

This code returns an array with only 2 elements, ignoring the null value. What I want to achieve is intArray.get(1) where it will return a null value.

Is there a way I can do that?

CodePudding user response:

ArrayList is so old school, better you using - if possible - list:

   val xs = listOf<Int?>(1,2,null,4,5)

   println(xs)          // [1, 2, null, 4, 5]

   println(xs.get(2))   // null 

CodePudding user response:

I've checked with:

fun main(args: Array<String>) {
    var intArray: ArrayList<Int?>? = null
    intArray = ArrayList()

    intArray.add(0)
    intArray.add(null)
    intArray.add(2)

    println(intArray)

    println(intArray.get(0))
    println(intArray.get(1))
    println(intArray.get(2))
}

The output contains null(s):

[0, null, 2]
0
null
2
  • Related