7

I have an ArrayList of String, let's say originalArrayList with some values

 final ArrayList<String> originalArrayList = new ArrayList<>();
            originalArrayList.add("value1");
            originalArrayList.add("value2");
            originalArrayList.add("value3");
            originalArrayList.add("value4");
            originalArrayList.add("value5");

  I copied this originalArrayList within inner class and removed some elements

button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ArrayList<String> tempArrayList = originalArrayList;
                                
                tempArrayList.remove(0); //Remove an element
               
            }
        });

But this is affecting the original ArrayList which is originalArrayList in my case.

How can I prevent this from happening ?

Shree Krishna
  • 8,474
  • 6
  • 40
  • 68

3 Answers3

5

As I know simply there are two ways to solve your issue,

  • Create new ArrayList and add each element of originalArrayList using loop (Not recommended, Because of unncessesory memory consuming task)

  • Clone the originalArrayList to tempArrayList.

Adding each element in new ArrayList looks something like this

    ArrayList<String> tempArrayList = new ArrayList<>();
    for (String temp : originalArrayList) {
          tempArrayList.add(temp);
      }

Cloning the ArrayList looks like this which I will recommend

ArrayList<String> tempArrayList = (ArrayList<String>) originalArrayList.clone();
Shree Krishna
  • 8,474
  • 6
  • 40
  • 68
1

What's happening on the assign statement is a shallow copy, which means two variables point to the same memory location, hence both of them gets changed.

What you can do is clone the ArrayList to create a new instance of the ArrayList:

ArrayList<String> tempArrayList = (ArrayList<String>) originalArrayList .clone();

Jude
  • 545
  • 3
  • 20
1

ArrayList offers a constructor that copies any Collection passed in.

ArrayList<String> tempArrayList = new ArrayList<String>(originalArrayList);
Ken Koster
  • 408
  • 3
  • 9