Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change elements of ArrayList in It's duplicate without affecting the original one?

Tags:

java

android

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 ?

like image 865
user5995765 Avatar asked Feb 29 '16 05:02

user5995765


1 Answers

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();
like image 151
Shree Krishna Avatar answered Nov 04 '22 19:11

Shree Krishna