Reputation: 3
I'm trying to put some objects in a mutableListOf, but all of them ended up overriding.
class Users {...}
class dbUsers{
var users = Users()
val list = mutableListOf(users)
fun addUser(phone: Int, name: String){
users.phone = phone
users.name = name
list.add(users)
}
}
fun main() {
var dbAccess = dbUsers()
dbAccess.addUser(8439, "Thiago")
dbAccess.addUser(12312, "Maria")
println(dbAccess.list[0].name)
println(dbAccess.list[1].name)
}
When We print at position 1, we see that was override
Upvotes: 0
Views: 2243
Reputation: 15244
You have initialized Users
object only once, at the class level in dbUsers
. You need to create new object everytime before adding the user to the list. Move the users
initialization within the method instead
class dbUsers{
val list = mutableListOf<Users>()
fun addUser(phone: Int, name: String){
var users = Users()
users.phone = phone
users.name = name
list.add(users)
}
}
Upvotes: 1
Reputation: 1649
It looks like the list
is referencing from users
and since users
itself is updated every time, you get this results.
There are two ways you can approach this issue ,
Creating a new user every-time calling addUser
, this is easy
If you have other data in Users
than name
and phone
, you can just make a DeepCopy of your object by add in a new function in your class copy()
like
class YourClass () {
// Your class other stuffs here
fun copy(): YourClass { //Get another instance of YourClass with the values like this!
val json = Gson().toJson(this)
return Gson().fromJson(json, YourClass::class.java)
}
}
then by using yourClassObject.copy() you will get a new instance with same values
fun addUser(phone: Int, name: String){
val newUsers = users.copy()
newUsers.phone = phone
newUsers.name = name
list.add(newUsers)
}
Upvotes: 0