Why do I need another new ArrayList instead of passing an existing one into ArrayList?

后端 未结 3 2100
温柔的废话
温柔的废话 2021-01-17 01:24

My question is:

ArrayList temp = new ArrayList(r);

Without this line, I am inserting nothing into res

3条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-17 01:48

    As the other answer said, doing:

    res.add(r)
    

    Adds a reference to the same object r is referring to, into the list. Effectively, what happens here is:

    • r refers to a list
    • That reference is passed as an argument to add
    • The reference to the list is stored inside res

    But notice that both r and the reference inside res are referring to the same object

    When you do the thing with the temp what happens is:

    • A new list is created, with copies of all the data in the original list referred to by r.
    • This list is assigned to temp
    • The reference to the new list is passed as an argument to add
    • The reference to the list is stored inside res

    So now r points to the original copy of the list, and the reference inside res points to the new copy of it. They are two distinct objects.

    Why is this important?

    Basically, your recursive step adds one element to r, calls find again, and then removes one element from r. The reference in r and res are passed down the recursion so it means those two same objects are passed down the recursion.

    But since after you return from the recursion, you actively remove one object from r, it means that at the end, when you go all the way up, there will be no more elements inside r.

    Since the reference stored inside res is pointing to the same object r is pointing to, not to a copy of it, it means that when you remove an item using r.remove(), that object becomes empty. But that's the same object that we are referring to from inside res. So at the end of the recursion, it will be empty.

    Think of it like a safe. Person A fills the safe with money. Then he gives person B a second key to the safe. Then he goes in with his original key, and takes out all the money. When B comes and opens the safe, it is empty!

    Copying the list is the equivalent of A giving B his own money to put in his own safe. A can remove as much money as he wants from his own safe, and it won't change the amount of money in B's safe.

提交回复
热议问题