Abdalla Maged
Abdalla Maged

Reputation: 55

Mutable array get overridden when get asserted to another variable

I have A simple case where I Have "List A" with 5 values and another "List B" acts As TempList holding "List A" values now when I call "list_A.clear()"
"list_B" also get Cleared why?

val List_A: MutableList<String> = ArrayList<String>()


List_A.add("index_1")
List_A.add("index_2")
List_A.add("index_3")
List_A.add("index_4")
List_A.add("index_5")

val  List_B = List_A
List_A.clear()

Result

List_A-----Size--------> 0
List_B-----Size--------> 0

Please Note that it works as expected when I define "List_B" as

var List_B: MutableList<String> = ArrayList<String>()
  then
List_B.addAll(List_A) 

Result

List_A-----Size--------> 0
List_B-----Size--------> 5

Does kotlin passes List_A variable Referance to List_B ?

Upvotes: 1

Views: 366

Answers (3)

Willi Mentzel
Willi Mentzel

Reputation: 29844

listA and listB both hold the same reference the time you call clear().

What you need to do is to make a copy of listA by calling toMutableList().

val listA = ArrayList<String>()

listA.add("index_1")
listA.add("index_2")
// ...

val listB = listA.toMutableList()
listA.clear()
// listB will be unchangend

Note:

  • You should stick to Kotlin's naming conventions, so your variables should be in camel-case without underscore.
  • The type of listA can be inferred, so there is no need to specifiy the type explicitely.

Upvotes: 2

Sergio
Sergio

Reputation: 30645

When you create an object and assign a reference to that object to List_A, a memory is allocated for that object and it has some address, say @eae072e. List_A is a reference to that object. When you create a variable List_B and assign to it List_A, they both refer to the same address in memory @eae072e. So when you use one of them to manipulate with data, this manipulation will be reflected in both of them - in List_A and List_B.

To avoid it new instance of List_B should be created:

var List_B: MutableList<String> = ArrayList<String>()
List_B.addAll(List_A) 

And then you can clear the list List_A and it not be reflected in List_B:

List_A.clear() 
// List_A is empty, List_B will contain items

Upvotes: 2

alextcn
alextcn

Reputation: 529

Does kotlin passes List_A variable Referance to List_B ?

Exactly. Both List_A and List_B refer to the same address in memory. If you want to make a copy you need to create a new ArrayList and add all elements into it with addAll. After that you may clear List_A.

Example

val listA: MutableList<String> = mutableListOf("index_0", "index_1", "index_2")
val listB: MutableList<String> = mutableListOf()
listB.addAll(listA)
listA.clear()

Although it'll work fine with String in your case, you must understand that new list contains same objects (reference to the same objects), not a copy of them. So if you don't clear listA and change an element of it, that element will also be changed in listB accordingly.

Upvotes: 2

Related Questions