Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Arraylist value changes automatically KOTLIN

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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])]

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading