【问题标题】:trying to remove a specific object from arraylist试图从 arraylist 中删除特定对象
【发布时间】:2014-10-07 18:37:57
【问题描述】:
    class EX6
    {
        private int value;

        public static void main(String [] args)
        {
            Scanner input = new Scanner(System.in);
            System.out.println("Enter some numbers (all on one line, separated by spaces):");
            String line = input.nextLine();
            String[] numbers = line.split(" +");
            ArrayList<Integer> a = new ArrayList<Integer>();

            for(int i=0; i<numbers.length; i++)
                a.add(new Integer(numbers[i]));
            System.out.println("The numbers are stored in an ArrayList");
            System.out.println("The ArrayList is "+a);

            EX6 ex = new EX6();
            ex.value = Integer.parseInt(JOptionPane.showInputDialog("Enter a number"));

            System.out.println(removeNumber(a,ex));
        }

        public static <T> ArrayList<T> removeNumber(ArrayList<T> a, EX6 e)
        // Adds n after every occurrence of m in a, constructively.
        {
            ArrayList<T> b = new ArrayList<T>();
            for(int i=0; i<a.size(); i++)
            {
                if(a.get(i) == e)
                {
                    a.remove(i);
                }
            }
            return a;

如果我在ArrayList 中输入值[5,12 ,4, 16,4],在JOptionPane 中输入4,我想从列表中删除所有4

我如何将 ex.value 传递给方法 removeNumber()???

【问题讨论】:

  • a.removeAll(Collection.singletonList(e)) 有什么问题你也拆分应该是 line.split("\\s+");
  • 正确的方法是使用迭代器 See this Answer
  • 如果我输入,没有任何反应,仍然得到 [5,12,4,16,4]
  • 以前没用过Iterators,有没有别的办法
  • 稍慢的替代选项(已授予)但您可以遍历原始列表并将元素复制到新列表,但前提是它们不等于您不想要的值新列表。

标签: java arraylist


【解决方案1】:

你可以重复使用 ArrayList.remove(Object)

ArrayList al = ...; int elementToRemove = ...; boolean found; do { found = al.remove((Integer)elementToRemove); } while (found);

【讨论】:

    【解决方案2】:

    你可以试试这个,只要定义Iterator和通过它的迭代器,找到你要删除的匹配元素,然后从迭代器中删除。它将删除 Arraylist 中的元素,因为 Iterator 指的是 Arraylist。

    public static <T> ArrayList<T> removeNumber(ArrayList<T> a, EX6 e)
    {
           Iterator i = a.iterator();
           while(i.hasNext())
           {
               if(i.next().equals((Integer)e.value))
               {
                i.remove();
               }
           }
           return a;
    }
    

    【讨论】:

      猜你喜欢
      • 2021-08-02
      • 2012-01-21
      • 2021-03-11
      • 2015-08-02
      • 1970-01-01
      • 1970-01-01
      • 2015-08-05
      相关资源
      最近更新 更多