java - arraylist.remove 无法正常工作

标签 java arrays arraylist

我有一个已排序的整数数组,想要删除重复项,我编写了以下代码

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/

相关文章:

C - 字符串数组(二维数组)和内存分配给我带来了不需要的字符

计算列表中元素平均值的Java库/数据结构?

java - 创建多个围绕 Pane 的球

java - 使用 JButton 和 JTabbedPane 从 JTextArea 获取文本

java - 无法回滚 GAE 部署事务

arrays - 为什么 Rust 以特定于体系结构的方式生成 LLVM IR,并对可变静态变量使用空数组?

Python 列表([])和 []

java - 为什么存在私有(private)静态方法,这些方法不在任何静态上下文中被调用?

java - 为请求映射 header spring 创建自定义注释

java - 使用 jdk 1.6 部署 war alltough 时获取 "Unsupported major.minor version 51.0"