So, I've a Data class Cars
.
When I first start activity, I'd create a list and add few objects:
val listA: ArrayList<Cars> = ArrayList()
listA.add(*API response objects*)
Everything is good till the moment I decide to create different list and add this list content (basically do a copy):
val listB: ArrayList<Cars> = ArrayList()
listB.addAll(listA)
Then I decide to do some removal commands like:
if (imFeelingLucky) listB.removeAt(position)
Problem:
Changes made to listB
also take affect on listA
(when I delete items from listA
it automatically deletes items from listB
). What am I missing? Why is this happening? I'm trying to change "content" of the list, not change "objects". How to avoid this?
CODE:
I've two dimensional list - list of cars and inside I've car colors.
Original list (I want to copy elements and not affect this one): listA
List<Cars>:
Car#1:
*name_of_car
*car_colors: List<CarColors> ...
Car#2:
*name_of_car
*car_colors: List<CarColors> ...
Car#3:
*name_of_car
*car_colors: List<CarColors> ...
listC - contains colors for cars. Basically for for-loop
.
class testA {
val listA: ArrayList<Cars> = ArrayList()
init {
getData()
changeData()
}
private fun getData() {
listA.add(..getting data and population listA)
}
private fun changeData(): List<Cars> {
val listB: List<Cars> = ArrayList()
listB.addAll(listA)
for (carPosition in listC.size - 1 downTo 0) {
for (carColorPosition in listC[carPosition].size - 1 downTo 0) {
if (!listC[carPosition][carColorPosition]) {
listB[carPosition].options.removeAt(carColorPosition)
}
}
}
for (itemToRemovePosition in listB.size - 1 downTo 0) {
if (listB[itemToRemovePosition] == 0) {
listB.removeAt(itemToRemovePosition)
}
}
return listB
}
}