Java 删除ArrayList中的重复项
对于这个赋值,我将编写一个RemovedUpplicates方法,该方法将字符串的排序ArrayList作为参数,并从列表中消除任何重复项 例如,假设名为list的变量包含以下值:Java 删除ArrayList中的重复项,java,arraylist,Java,Arraylist,对于这个赋值,我将编写一个RemovedUpplicates方法,该方法将字符串的排序ArrayList作为参数,并从列表中消除任何重复项 例如,假设名为list的变量包含以下值: {"be", "be", "is", "not", "or", "question", "that", "the", "to", "to"} {"be", "is", "not", "or", "question", "that", "the", "to"} 调用RemovedUpplicates(列表)后,列
{"be", "be", "is", "not", "or", "question", "that", "the", "to", "to"}
{"be", "is", "not", "or", "question", "that", "the", "to"}
调用RemovedUpplicates(列表)后,列表应存储以下值:
{"be", "be", "is", "not", "or", "question", "that", "the", "to", "to"}
{"be", "is", "not", "or", "question", "that", "the", "to"}
我几乎把它记下来了,但出于某种原因,如果列表中包含
["duplicate", "duplicate", "duplicate", "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);
}
}
}
}
private static void removeDuplicates(ArrayList东西){
对于(int i=0;i
问题是,即使找到重复的,也要执行“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.
问题是,即使在发现重复项时也会使用“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.
每次删除ArrayList中的条目时,其大小都会减小
因此
thing.size()
将减小。每次删除ArrayList中的条目时,其大小都会减小
因此
thing.size()
将减少。将为您提供一个Java集合技巧:将列表转换为一个集合,根据定义,该集合只保留唯一值,然后再次将其转换回列表 将为您提供一个Java集合技巧:将列表转换为一个集合,根据定义,该集合只保留唯一值,然后再次将其转换回列表 提示:尝试使用该小示例单步遍历代码,并关注thing.size()
在循环每次迭代后如何更改。提示:尝试使用该小示例单步遍历代码,并关注thing.size()
在循环每次迭代后如何更改。