J.H*_*ell 0 java arraylist duplicates
我的 Java 代码有一些问题。我应该使用循环而不是任何其他方法。假设我的ArrayList 包含
【狗猫狗狗猫狗马】
我的目标也是删除 Dog 和 Cat 的副本,因此我的最终结果等于
[狗猫马]
public void removeDouble(){
int counter = 0;
for (int i = 0 ; i < animals.size(); i++) {
for (int j = 1+i; j < animals.size() ; j++)
//don't start on the same word or you'll eliminate it.
if ( animals.get(j).equals( animals.get(i) ) ) {
animals.remove(animals.get(j));
counter++;
}
}
}
Run Code Online (Sandbox Code Playgroud)
感觉“逻辑”是正确的,但我的代码运行得不太好。有人可以帮我一点吗?
你可以这样做。
ArrayList<String>list=new ArrayList<>();
list.add("A");
list.add("B");
list.add("C");
list.add("A");
System.out.println("Before "+list); // output[A,B,C,A]
Set<String> listWithoutDuplicates = new LinkedHashSet<String>(list);
list.clear();
list.addAll(listWithoutDuplicates);
System.out.println("list without duplicates : " + list);// output[A,B,C]
Run Code Online (Sandbox Code Playgroud)