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 ?
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With