对于这个任务,我将编写一个方法 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"]
它将删除除两个之外的所有内容,从而导致 [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);
}
}
}
}