我有一个测验计划,但一小部分不起作用.基本上,我有一个ArrayList
包含10个(或更多,无关紧要)的问题对象,我稍后可以参考.
无论如何,当我想使用时ArrayList.remove(index)
,它不会删除该对象!老实说,我不知道该怎么做.
(Key Search是另一个接受字符串(key)的类,并在测验arraylist中搜索它.它返回一个不包含关键字的问题的arraylist,从而让我从整个问题数组中删除它们.)
ArrayListindexAt = 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 !!
请参见ArrayList #remove(Object):
从此列表中删除指定元素的第一个匹配项(如果存在).如果列表不包含该元素,则不会更改.更正式地说,删除具有最低索引的元素
i
,使得(o==null ? get(i)==null : o.equals(get(i)))
(如果存在这样一个元素).返回true
此列表是否包含指定元素(或等效地,如果此列表因调用而更改).
和ArrayList #remove(int):
删除此列表中指定位置的元素.将任何后续元素向左移位(从索引中减去一个).
您使用第一种方法,但您可以轻松地更改它:
Questions.remove(indexAt.get(i).intValue());
但你也订购了你的indexAt
下降.