Understanding this removeAll java method with arrayList

后端 未结 3 557
佛祖请我去吃肉
佛祖请我去吃肉 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:57

    Why do we start the second for-loop one after where the last one was?

    Each time an occurence is found, we want to left shift by 1 all following values of the arraylist.

    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?

    j-1 is used to shift left by 1 .

    Why after this second loop is over is there the line: list.set(list. sise () - 1, 0) ?

    We shifted values left, but the value at the last index (size-1) has not been replaced by anything, we want it to be 0 .

    why the i--?

    As the value at the current index has been overwritten by another value, we want to start next iteration at the same index (i-- compensating i++).

提交回复
热议问题