【发布时间】:2016-04-01 02:32:53
【问题描述】:
我有一个测验程序,但一小部分无法运行。基本上,我有一个ArrayList<Object>,其中包含 10 个(或更多,没关系)我可以稍后参考的问题对象。
无论如何,当我想使用ArrayList.remove(index) 时,它不会删除那个对象!老实说,我不知道该怎么办。
(Key Search 是另一个接受字符串 (key) 并在测验数组列表中搜索它的类。它返回一个不包含关键字的问题的数组列表,从而让我将它们从整个问题数组中删除.)
ArrayList<Integer> 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!!
【问题讨论】:
-
那么我的问题数不应该是 5,因为我从 Questions 数组列表中删除了 1、2、3、4、6,因此,当我使用 Questions.size() 时,它应该返回5,不是 10
-
能否添加
Questions的代码以进一步澄清? -
确保您的
remove使用整数,因为对象将作为键而不是索引删除(可能找不到键)。 -
嗯,当我用数字而不是“indexAt.get(i)”进行硬编码时,它正在工作。为什么我的 indexAt(整数类型)不起作用..)
-
我不认为你在这里按索引删除。由于“indexAt”返回了 Object 的子类型,它可能会尝试从“问题”列表中删除传递的对象。 (换句话说,我认为它不会将整数拆箱为 int)