Home > OS >  ArrayList get value of another ArrayList
ArrayList get value of another ArrayList

Time:05-07

I have a problem with ArrayList. I have 2 ArrayList and they are dependent.

class MainActivity : AppCompatActivity() {

    var arrayList1 = arrayListOf<String>()
    var arrayList2 = arrayListOf<String>()
    lateinit var binding: ActivityMainBinding
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)
        clickOnButton()
        arrayList1 = arrayListOf<String>("a", "b", "c")
        arrayList2 = arrayList1
        arrayList2.clear()
        println("ARRAYLIST: $arrayList1") //return me empty []
    }

I want to keep values in arrayList1. How I can do that?

CodePudding user response:

You can create a new array list with the old array list elements like this:

arrayList1 = arrayListOf<String>("a", "b", "c")
arrayList2 = arrayListOf(arrayList1)
arrayList2.clear()
println("ARRAYLIST: $arrayList1") // will print [a, b, c]

CodePudding user response:

You could use this function:

fun cloned(arrayList: ArrayList<Any>): ArrayList<Any> {
return arrayList.map {
when (it) {
  is ArrayList<*> -> cloned(it.toList() as ArrayList<Any>)
  else            -> it
      }
   } as ArrayList<Any>
}

It's for deep cloning but it will work. But you can use a normal for loop either:

for (i in arrayList1) {
    arrayList2.add(i)
}
  • Related