gpt4 book ai didi

java - 删除 ArrayList 中的重复项

转载 作者:太空宇宙 更新时间:2023-11-04 07:21:23 25 4
gpt4 key购买 nike

对于此作业,我将编写一个方法removeDuplicates,该方法将排序的字符串ArrayList 作为参数,并从列表中消除任何重复项。

例如,假设名为 list 的变量包含以下值:

{"be", "be", "is", "not", "or", "question", "that", "the", "to", "to"} 

调用removeDuplicates(list)后,列表应存储以下值:

{"be", "is", "not", "or", "question", "that", "the", "to"}

我几乎已经把它记下来了,但由于某种原因,如果列表包含

["duplicate", "duplicate", "duplicate", "duplicate", "duplicate"] 

它将删除除两个之外的所有内容,从而导致[重复,重复]而不是

这是我的代码:

private static void removeDuplicates(ArrayList<String> thing) {
for (int i = 0; i < thing.size(); i++) { // base word to compare to
String temp = thing.get(i);

for (int j = 0; j < thing.size(); j++) { // goes through list for match
String temp2 = thing.get(j);

if (temp.equalsIgnoreCase(temp2) && i != j) { // to prevent removal of own letter.
thing.remove(j);
}
}
}
}

最佳答案

问题是,即使找到重复项,您也会执行“j++”。一旦你做了“thing.remove(j);”它本质上是将所有内容向下移动一个索引值,因此您不必增加 j。

示例:

{ duplicate, duplicate, duplicate, duplicate, duplicate }

i iteration 1:
i=0 [dup, dup, dup, dup, dup]
j=0 [dup, dup, dup, dup, dup]
remove=1
j=1 [dup, dup, dup, dup]
remove=2
j=2 [dup, dup, dup]

i iteration 2:
i=1 [dup, dup, dup]
remove=0
j=0 [dup, dup]
j=1 [dup, dup]

[dup, dup]

i iteration 3 stops since 3>size of list.

关于java - 删除 ArrayList 中的重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19261292/

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