'MutableLiveData containing List<> always passed by reference. Want to pass it by value

I have a seperate class for my sqlite operations named DBOperations.java which fetch data and pass all data to my ViewModel named HomeActivityViewModel.java through a interface named DBOperationsListener

public interface DBOperationsListener {
    void itemDataLoaded(List<ItemData> itemDataList);
}

my HomeActivityViewModel.java

public class HomeActivityViewModel extends AndroidViewModel implements DBOperations.DBOperationsListener {

    private DBOperations dbOperations;
    private MutableLiveData<List<ItemData>> orderItemDataMLData = new MutableLiveData<>();
    private MutableLiveData<List<ItemData>> returnItemDataMLData = new MutableLiveData<>();
    
    public HomeActivityViewModel(@NonNull Application application) {
        super(application);
        this.application = application;
        dbOperations = new DBOperations(application, this);
        dbOperations.loadItemData();
    }

    public MutableLiveData<List<ItemData>> getOrderItemDataMLData() {
        return orderItemDataMLData;
    }

    public MutableLiveData<List<ItemData>> getReturnItemDataMLData() {
        return returnItemDataMLData;
    }

    @Override
    public void itemDataLoaded(List<ItemData> itemDataList) {
        orderItemDataMLData.postValue(new ArrayList<>(itemDataList));
        returnItemDataMLData.postValue(new ArrayList<>(itemDataList));
    }

on my FirstFragment

private List<ItemData> itemDataList;
homeActivityViewModel.getOrderItemDataMLData().observe(getViewLifecycleOwner(), (itemData) -> {
    itemDataList = itemData;
});

then later on the same fragment I get an item and update the values of that item as this

ItemData item = itemDataList.get(index);
item.setValue(value);

When I update that value both MutableLiveData lists (orderItemDataMLData and returnItemDataMLData) on the HomeActivityViewModel item value is set to the value that has assigned on the fragment.

What I have Tried : changed method itemDataLoaded to

@Override
public void itemDataLoaded(List<ItemData> itemDataList) {
    List<ItemData> itemDataArrayList1 = new ArrayList<>();
    itemDataArrayList1.addAll(itemDataList);
    orderItemDataMLData.postValue(itemDataArrayList1);
    List<ItemData> itemDataArrayList2 = new ArrayList<>();
    itemDataArrayList2.addAll(itemDataList);
    returnItemDataMLData.postValue(itemDataArrayList2);
}

but still both MutableLiveData is updated when the value assigned.

I cannot understand why it is happening. since I have created two new ArrayLists before assigning the value.

please follow this link to the example app which creates this problem



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source