我有一个已排序的整数数组,想要删除重复项,我编写了以下代码
package practice;
import java.util.*;
public class pb1 {
public static void removeDup(int[] theArray){
ArrayList<Integer> hold=new ArrayList<Integer>();
for(int i=0;i<theArray.length-1;i++){
hold.add(theArray[i]);
//System.out.println(hold);
}
for(int i=0;i<hold.size()-1;i++){
if(hold.get(i)==hold.get(i+1)){
hold.remove(i);
}
}
System.out.println(hold);
}
public static void main(String[]args){
int[] now={1,1,2,2,3,4,4,4,5,5,5,5};
removeDup(now);
}
}
尝试使用 arraylist.remove 方法删除重复项,但我仍然可以在打印的数组列表中看到重复项。我不知道为什么,有人可以帮助我吗?谢谢
最佳答案
替代解决方案。这利用了 Set
不允许重复条目的事实,并极大地简化了您的代码。
public class pb1
{
public static void removeDup(int[] theArray)
{
Set<Integer> hold=new TreeSet<Integer>();
for(int i=0;i<theArray.length-1;i++)
{
hold.add(theArray[i]);
}
System.out.println(hold);
}
public static void main(String[]args)
{
int[] now={1,1,2,2,3,4,4,4,5,5,5,5};
removeDup(now);
}
}
输出:
[1, 2, 3, 4, 5]
关于java - arraylist.remove 无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22469366/