Jaimin Modi
Jaimin Modi

Reputation: 1667

Issue in adding new value in ArrayList at 0th position

I have ArrayList of my model/pojo class. Which has below values which I am getting in my logcat :

BatteryDetailsHistory(dates=10 01 2022, dateNumber=10, chargeOverTime=94, avgTemperature=21.9385, averageChargeDischarge=-2.1234)

Now, here at specific situation I have to add one value of the object BatteryDetailsHistory at 0th position in the arraylist of this model/pojo.

So, I have done it as below :

var objNew = list[0]
objNew.averageChargeDischarge = "0"
list.add(0, objNew)

But after that What I am getting is as below :

BatteryDetailsHistory(dates=10 01 2022, dateNumber=10, chargeOverTime=94, avgTemperature=21.9385, averageChargeDischarge=0)

BatteryDetailsHistory(dates=10 01 2022, dateNumber=10, chargeOverTime=94, avgTemperature=21.9385, averageChargeDischarge=0)

You can see I have tried changing the value of averageChargeDischarge to 0 But after adding new object of pojo/model to my list, I am getting both the data in list with values 0 for averageChargeDischarge

What might be the issue ?

Upvotes: 0

Views: 716

Answers (2)

Sergio
Sergio

Reputation: 30595

If you want just change a property of the first object in the list, you can access it by index:

 list[0].averageChargeDischarge = "0"

If you want to preserve the first object with its initial data in the list, then you need to make a copy of it, e.g. create a new object:

// If object(BatteryDetailsHistory) is a data class
val objNew = list[0].copy(averageChargeDischarge = "0")
list.add(0, objNew)

// If object(BatteryDetailsHistory) is not a data class
val objOld = list[0]
val objNew = BatteryDetailsHistory(/*copy all properties from objOld*/, averageChargeDischarge = "0")
list.add(0, objNew)

Upvotes: 1

Todd
Todd

Reputation: 31660

This is happening because you are dealing with one object.

Suppose you have a list with an instance of SomeObject in it, which we will call SomeObject1:

[SomeObject1]

Your first line of code, gets a reference to SomeObject1:

var objNew = list[0]

So objNew is a reference to SomeObject1. And now you change a field in SomeObject1:

objNew.averageChargeDischarge = "0"

So now SomeObject1 has averageChargeDischarge equal to "0". And then you go insert that same object back into the list:

list.add(0, objNew)

And your list looks like this now:

[SomeObject1, SomeObject1]

You never had two instances of the object, you always only ever had one of them. This is why it appears to show up twice.

Upvotes: 0

Related Questions