Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ArrayList problem while deleating

hi i have a problem with Arraylist objects here is my code

ArrayList<String> globlalArrayList = new ArrayList<String>(); //declared in some other class
ArrayList<String> TempArray = getsomeTempObjects()//method
globlalArrayList = TempArray;
TempArray.clear();  //Here the Problem

in above code i want to clear all TempArray obj. but it is also clearing globlalArrayList Can Any one tell me what happening and how can i achieve this problem

like image 377
Bad Boy Avatar asked Jul 27 '26 19:07

Bad Boy


1 Answers

You should not use just reference copy. Use addAll():

globlalArrayList.addAll(TempArray);

What you do now is just referencing one object from two references. If you make manipulation one, it is all refletected on the second, as they reference to 1(one) object.

P.S. Java uses camelCase style, so please name your array as tempArray.

like image 149
Vladimir Ivanov Avatar answered Jul 30 '26 07:07

Vladimir Ivanov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!