Joey Vagedes Joey Vagedes - 3 months ago 16x
Android Question

ArrayList<ArrayList<String>> is being cleared when clearing a different ArrayList<String>

Hello I have a Class for Global Variables. One of the Functions within that Class is used to clear one of my ArrayList's. The only issue, is that it is clearing Two of my ArrayLists and I can't figure out why. All it is suppose to clear is m_listItems.

Before the Clear Runs:

After the Clear Runs:

This function adds the ArrayList "m_listItems" to the double Array List.

public void addGrouptoList(){
ArrayList myArray = Global.m_listItems;

This function should clear ONLY m_listItems but it clears both:

public void ClearNameList(){

This is how I created the two ArrayList's

private static ArrayList<ArrayList<String>> groupCollection= new ArrayList<>();
private static ArrayList<String> m_listItems = new ArrayList<String>();

Any Help would be much appreciated. Whether it be a work around or why its messing up!

I have done a lot of googling and I think the issue is because I'm doing add(global.m_list_items), so when i clear m_list_items, it clears it in my other array also... is there a work around for this? I read that Static is what is causing the issue but I need that for my global variable. I can't seem to find a workaround in google.



array don't holds objects but pointers to objects making new array and adding object to the second array don't make a copy of objects ! Modifying object in one array you are modifying it in the second

u need to do

new ArrayList<>(oldArray);

read more about shallow and deep copy

in example above we use a copy constructor other method is to use

How do I copy an object in Java?

Deep copy, shallow copy, clone


i like your style :) total violation of all rules & conventions :) if u need help cal me anytime !!!