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

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

问题描述

此方法的职责是从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循环? 为什么我们要使用先前的loops变量并将其加1? 为什么在第二个循环中我们使用参数列表"并使用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了解此remove方法解决方案的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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