Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

copy one arraylist to another arraylist in kotlin

I am trying to copy one ArrayList to another ArrayList in Kotlin

1st ArrayList:

private var leadList1: ArrayList<Lead> = ArrayList()

2nd ArrayList:

val leadList2: ArrayList<Lead?>?

I tried to use addAll(). leadList1.addAll(leadList2)

But its not working.

Error showing:

Required: Collection<Lead>
Found: kotlin.collections.ArrayList<Lead?>?
like image 256
sagar suri Avatar asked May 06 '18 14:05

sagar suri


2 Answers

This isn't safe to do, because your first list can only contain objects of type Lead, while your second one has Lead? as its type parameter, meaning that it might contain null values. You can't add those to the first list.

The solution for this problem will depend on your context, but you can either let the first list contain nullable elements too:

private var leadList1: ArrayList<Lead?> = ArrayList()

Or you can add only the non-null elements of the second list to the first one:

leadList1.addAll(leadList2.filterNotNull())

And in either case, you'll have to perform a null check on leadList2, because the entire list itself is marked as potentially null as well, signified by the last ? of the type ArrayList<Lead?>?.

if (leadList2 != null) {
    leadList1.addAll(leadList2.filterNotNull())
}
like image 129
zsmb13 Avatar answered Sep 30 '22 12:09

zsmb13


You can simply pass another List instance into the constructor of your new List

val originalList = arrayListOf(1,2,3,4,5)

val orginalListCopy = ArrayList(originalList)
like image 39
trOnk12 Avatar answered Sep 30 '22 10:09

trOnk12