Understanding this removeAll java method with arrayList

后端 未结 3 555
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-07 06:34

This method\'s duty is to remove all occurrences of the value toRemove from the arrayList. The remaining elements should just be shifted toward the beginning of

3条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-07 06:55

    Why another for-loop? Why do we start the second for-loop one after where the last one was? Why within that second for loop do we use list.set(), I understand that set method takes in two arguments, the index position, and the element to sub into that designated position. Why j - 1?

    The method does everything the documentation says. The inner loop shifts the elements left by one.

    for (int j = i + 1; j < list.size(); j++) {
        list.set(j - 1,       //The index before j (that is, j - 1) is set to...
                list.get(j)); //the current element.
        }
    }
    

    Starting at the element after the found index, it sets the one to the left to the current element. Eventually, you'll end up with all elements having been shifted left.

    list.set(list.size() - 1, 0);
    

    This sets the last element to zero. Since your list has had one element removed, you need to get rid of the last one because everything has been shifted.

    Example:

    In these examples, ^ is i and * is j.

    0 1 2 3 4
    

    Say I want to remove 2.
    First, I'll loop until I find 2.

    0 1 2 3 4
        ^ index: 2
    

    Now, I'll shift everything left to remove that element. Because we're shifting left, we need to start at i + 1 (hence the for-loop starting at i + 1.

    0 1 3 3 4
        ^ * (replaced the one before *)
    

    Next, we do it again.

    0 1 3 4 4
        ^   *
    

    Now we're done.

    list.set(list.size() - 1, 0);

    However, 4 is left at the end. We need to remove that because we removed an element, and the list is one element shorter. So, we set the last element to zero to remove it (of course, this assumes zero is not a valid value in the list).

    Note:

    I would strongly suggest doing list.remove(list.size() - 1) instead of the call to set. This actually removes the last item and does not leave it with a "magic number" default value.

    Why the i--?

    You need i-- because everything has been shifted left, so you'll need to update the index 1 to the left, namely by subtracting one. (Actually, what you need to do is start the iteration at the same index, but since the for-loop executes i++ every iteration you need to do i-- to "cancel" it out.)

提交回复
热议问题