Confusion with Clear() method of ArrayList

Hi,

Check out the following lines.

ArrayList list1,list2;
list1.Clear();
list1 = list2;

Now, my question is, does calling the Clear() method matter here It shouldn't isn't it because in the next line we are assigning another list2 to list1 (this is by reference isn't it). So the presence or absence of Clear() method should affect list1.

But that is not the case for me. If I call Clear() the contents are getting erased even after I assigned list2 to list1. What is wrong here

Thank you.




Answer this question

Confusion with Clear() method of ArrayList

  • Andras Tantos

    Hi,

    Thank you for the reply. I got it. I think I did what you mentioned in your last step. Assigned list2 to list1 and then called Clear() on list1. Sorry for the trouble and thanks once again.



  • Bobby R

    Hi,
    I didn't quite understand what is your problem. I'll give a simple example with the clear method:

    ArrayList list1 = new ArrayList(), list2 = new ArrayList();
    list1.Add(1);
    list1.Add(2);
    list1.Add(3);
    // at this point list1 contains 3 elements (1,2,3)
    list2.Add(7);
    list2.Add(8);
    list2.Add(9);
    // at this point list2 also contains 3 elements (7,8,9)
    list1.Clear();
    // at this point list1 has 0 elements but list2 remains the same
    list1 = list2;
    // at this point list1 and list2 point to the same list that contains 3 elements (7,8,9)
    // changing either list1 or list2 will reflect in changes list2 or list1 respectively.
    list1.Clear();
    // both list1 and list2 point to the same list that has 0 elements

    Hope this helps, if not, just say something that I'll be glad to try and help you.


  • Confusion with Clear() method of ArrayList