Home > database >  Arraylist value changes automatically KOTLIN
Arraylist value changes automatically KOTLIN

Time:01-13

I have an arraylist inside another arraylist , when i enter values, value of the previous arraylist automatically changes to last entered value.

Code is as follows

Question.class

data class Question(
var id: String,
var question: String,
var correct: String,
var answer: ArrayList<String>
)

MainActivity

        answers.add("1234")
        answers.add("234")
        questions.add(Question("1","1","1",answers))
        Log.d("12345",questions.toString())

        answers.clear()
        answers.add("5678")
        answers.add("789")
        questions.add(Question("2","2","2",answers))
        Log.d("12345",questions.toString())

o/p

D/12345: [Question(id=1, question=1, correct=1, answer=[1234, 234])]

D/12345: [Question(id=1, question=1, correct=1, answer=[5678, 789]), Question(id=2, question=2, correct=2, answer=[5678, 789])]

CodePudding user response:

You only have one list of answers here. Each question gets a reference to that single list. Instead, you should create a new list of answers for each question. To understand this better, I suggest you read about references in Kotlin.

  • Related