gpt4 book ai didi

java - 使用 arrayList 理解这个 removeAll java 方法

转载 作者:行者123 更新时间:2023-11-30 07:56:38 27 4
gpt4 key购买 nike

此方法的职责是从 arrayList 中删除所有出现的值 toRemove。剩余的元素应该只是移向列表的开头(大小不会改变)。最后的所有“额外”元素(无论 toRemove 在列表中出现多少次)都应该用 0 填充。该方法没有返回值,如果列表没有元素,它应该只是没有效果。不能使用 ArrayList 类中的 remove()removeAll()

方法签名是:

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 整数。在这一点之后,我迷路了。

为什么还有一个 for 循环?为什么我们在上一个循环之后开始第二个 for 循环?为什么在第二个 for 循环中我们使用 list.set(),我知道 set 方法有两个参数,索引位置和子到该指定位置的元素。为什么是 j-1?为什么在第二个循环结束后有一行: list.set(list.size()-1, 0) ?为什么 i--

有很多 Activity 部分,我想了解其中的逻辑。

谢谢

最佳答案

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?

该方法执行文档中所说的所有内容。内部循环将元素左移一位。

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.
}
}

从找到的索引之后的元素开始,它将左边的元素设置为当前元素。最终,所有元素都将左移。

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

这会将最后一个元素设置为零。由于您的列表已删除一个元素,因此您需要删除最后一个元素,因为所有内容都已移动。

示例:

在这些示例中,^是我和 *j .

0 1 2 3 4

假设我要删除 2。
首先,我将循环直到找到 2。

0 1 2 3 4
^ index: 2

现在,我将向左移动所有内容以删除该元素。因为我们向左移动,所以我们需要从 i + 1 开始(因此 for 循环从 i + 1 开始。

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

接下来,我们再来一遍。

0 1 3 4 4
^ *

现在我们完成了。

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

但是最后还剩4。我们需要删除它,因为我们删除了一个元素,而列表又短了一个元素。因此,我们将最后一个元素设置为零以将其删除(当然,这假设零不是列表中的有效值)。

注意:

我强烈建议做 list.remove(list.size() - 1)而不是调用 set .这实际上会删除最后一项,并且不会为其保留“魔数(Magic Number)”默认值。

Why the i--?

你需要i--因为所有内容都向左移动,所以您需要将索引 1 更新到左侧,即减一。 (实际上,您需要做的是在相同索引处开始迭代,但是由于 for 循环执行 i++ 每次迭代,您需要执行 i-- 以“取消”它出。)

关于java - 使用 arrayList 理解这个 removeAll java 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41962261/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com