当前位置:  开发笔记 > 编程语言 > 正文

Java ArrayList.remove()不起作用?

如何解决《JavaArrayList.remove()不起作用?》经验,为你挑选了1个好方法。

我有一个测验计划,但一小部分不起作用.基本上,我有一个ArrayList包含10个(或更多,无关紧要)的问题对象,我稍后可以参考.

无论如何,当我想使用时ArrayList.remove(index),它不会删除该对象!老实说,我不知道该怎么做.

(Key Search是另一个接受字符串(key)的类,并在测验arraylist中搜索它.它返回一个不包含关键字的问题的arraylist,从而让我从整个问题数组中删除它们.)

        ArrayList indexAt = new ArrayList();
        indexAt = keyWord.indexAt(); //returning the questions that need to be removed
        System.out.println("(1) Number of Questions: " + Questions.size()); //debugging
        for(int i = 0; i < indexAt.size(); i++)
        {

            Questions.remove(indexAt.get(i));

        }

        //prints out the questions that were removed (for my own reasoning)
        for(int i = 0; i < indexAt.size(); i++)
        {

            System.out.println(indexAt.get(i));
        }

        System.out.println("(2) Number of Questions: " + Questions.size()); //debugging

        Sorting sort = new Sorting(Questions);

输出如下所示:


(1)问题数量:10

1

2

3

4

6

(2)问题数:10


它应该删除索引1,2,3,4,6 !!



1> dur..:

请参见ArrayList #remove(Object):

从此列表中删除指定元素的第一个匹配项(如果存在).如果列表不包含该元素,则不会更改.更正式地说,删除具有最低索引的元素i,使得(o==null ? get(i)==null : o.equals(get(i)))(如果存在这样一个元素).返回true此列表是否包含指定元素(或等效地,如果此列表因调用而更改).

和ArrayList #remove(int):

删除此列表中指定位置的元素.将任何后续元素向左移位(从索引中减去一个).

您使用第一种方法,但您可以轻松地更改它:

Questions.remove(indexAt.get(i).intValue());

但你也订购了你的indexAt下降.

推荐阅读
刘美娥94662
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有