Joey Vagedes Joey Vagedes - 5 months ago 25
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:
http://i.stack.imgur.com/dN5n4.png

After the Clear Runs: http://i.stack.imgur.com/5eKfj.png

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

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


This function should clear ONLY m_listItems but it clears both:

public void ClearNameList(){
Global.m_listItems.clear();
}


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!

EDIT
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.

Thanks!

Answer

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

http://cs-fundamentals.com/java-programming/java-arrays-clone-shallow-deep-copy.php

How do I copy an object in Java?

Deep copy, shallow copy, clone

btw:

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

Comments