使用 arrayList 了解此删除方法解决方案 [英] Understanding this remove method solution with arrayList

查看:34
本文介绍了使用 arrayList 了解此删除方法解决方案的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此方法的职责是从 arrayList 中删除所有出现的值 toRemove.剩下的元素应该只是移向列表的开头.(大小不会改变.)末尾的所有额外"元素(无论列表中出现多少次 toRemove)都应该填充 0.该方法没有返回值,如果列表没有元素,它应该没有影响.不能使用 ArrayList 类中的 remove() 和 removeAll().

This methods duty is to remove all occurrences of the value toRemove from the arrayList. The remaining elements should just be shifted toward the beginning of the list. (the size will not change.) All "extra" elements at the end (however many occurrences of toRemove were in the list) should just be filled with 0. The method has no return value, and if the list has no elements, it should just have no effect. Cannot use remove() and removeAll() from the ArrayList class.

方法签名为:

public static void removeAll(ArrayList<Integer> list, int toRemove);

解决办法:

public static void removeAll(ArrayList<Integer> list, int toRemove) {
    for (int i = 0; i < list.size(); i++) {
        if (list.get(i) = toRemove) {
            for (int j = i + 1; j < list.size(); j++) {
                list.set(j - 1, list.get(j));
            }
            list.set(list.size() - 1, 0);
            i--;
        }
    }

我理解第一个 for 循环和 if 语句.因为人们想要一个一个地遍历整个 arrayList 并且对于每个索引,并且在 arrayList 中存在一个数字,检查它是否是,实际上是 toRemovee 整数.在这一点之后,我变得迷失了.

I understand the first for loop and the if statement well. Because one would want to iterate through the entire arrayList one-by-one and for each index with a number present in the arrayList check if it is, in fact the toRemovee integer. After this point I become lost.

为什么还有一个 for 循环?为什么我们要使用前面的循环变量并将其加 1?为什么在第二个循环中我们使用参数list"并使用 set 方法?为什么是 j - 1?为什么是 list.get(j)?为什么在第二个循环结束后有一行:list.set(list.sise() - 1, 0) ?为什么我--?

Why another for loop? Why are we taking the previous loops variable and adding 1 to it? why within this second loop are we using the parameters "list" and using a set method? why j - 1? why list.get(j)? Why after this second loop is over is there the line: list.set(list. sise () - 1, 0) ? why the i--?

有很多活动部分,我想了解其中的逻辑.

There are a lot of moving parts and I would like to understand the logic.

谢谢

推荐答案

请看下面了解详情(从分钟 5:50 或 5:57)

Please see the following to learn details (from minute 5:50 or 5:57)

https://www.youtube.com/watch?v=qTdRJLmnhQM

你需要第二个 for 循环,在你删除它的元素之后获取所有元素并将其向左移动一个,所以基本上它填充了删除它留下的空白空间所以这就是这个

You need the second for loop ,to take all elements after the element you’ve removed it and shift it over one to the left so basically it’s filling up the space that is left empty from removing it so this is what this is doing.

这篇关于使用 arrayList 了解此删除方法解决方案的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆