0

I have a List in a RecyclerView``. Whenever I change any object value in Onclick inside OnBindViewHolder the main list value changes. I want this but I cannot understand why it is taking place.

Does it guarantees that whenever I change object inside onBindViewHolder, it changes main List?

I think it is due to pass by reference or something.

public class AttendanceAdapter extends RecyclerView.Adapter<AttendanceAdapter.ViewHolder> {

    List<ChildAttendance> data ;


    public AttendanceAdapter(List<ChildAttendance> childList) {

        data=new ArrayList<>(childList);

    }


    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
         ChildAttendance child =  data.get(position);

         ((ViewHolder) holder).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                  child.setName("checked");
            }
        });
    }
}

child.setName("checked"); changes value in data. I have a large list. Does it always guarantees the main list changes when I change any object.

ישו אוהב אותך
  • 28,609
  • 11
  • 78
  • 96
everestkid
  • 148
  • 1
  • 9

1 Answers1

1

I have a List in a Recyclerview. Whenever I change any object value in Onclick inside OnBindViewHolder the main list value changes.

It's a correct behaviour in Java. It's because whenever you're passing a value of an object, you're passing a reference to it. So, whenever you're instantiating the adapter with the following line:

List<ChildAttendance> mainData; // assuming there are data here.
...
AttendanceAdapter adapter = new AttendanceAdapter(mainData);

Your AttendanceAdapter.data is pointing to the same location with mainData. In short, AttendanceAdapter.data is an alias for mainData object.

ישו אוהב אותך
  • 28,609
  • 11
  • 78
  • 96