使用ListIterator从列表中删除项目

时间:2012-09-19 02:52:25

标签: java arrays string list

代码:

 Random Picker = new Random();
 List<String> list = new ArrayList<String>();
  list.add("card1");
  list.add("card2");
  list.add("card3");


  ListIterator listIterator = list.listIterator();
  String c1, c2, c3;
  c1 = list.get(Picker.nextInt(list.size()));
  listIterator.remove();

执行此操作时,我收到java错误。我要做的是将c1设置为list.get(Picker.nextInt(list.size())); 然后从列表中删除所选卡。换句话说,我希望String c1从列表中随机选择,然后对于它选择要从列表中删除的卡,但保留在值c1中。我想我当前的代码不起作用,因为当我删除它所选择的内容时,它也会从字符串c1中删除该卡。我不知道如何正确地做到这一点。

2 个答案:

答案 0 :(得分:1)

您没有使用迭代器从集合中删除元素。您正在从刚刚实例化的迭代器中调用remove。如果您查看ListIterator文档,则会看到remove

  

此调用只能在每次调用next或previous时进行一次。只有在最后一次调用next或previous之后没有调用ListIterator.add时才能进行此操作。

这意味着,如果没有在迭代器上调用next()来获取第一个元素,那么你仍处于非法状态。

在任何情况下都根本不需要使用迭代器。来自remove(int index)的{​​{1}}方法可以解决问题:

List<E>

答案 1 :(得分:1)

我同意杰克。此外,您可以通过调用Random来使用Collections.shuffle(list)类替换。顾名思义,它将为您随机化您的列表。使用listIterator,您可以遍历列表并选择您的卡片,将它们存储在另一个列表中。它看起来像是:

List<String> list = new ArrayList<String>();
list.add("card1");
list.add("card2");
list.add("card3");

Collections.shuffle(list);

ListIterator<String> listIterator = list.listIterator();
List<String> pickedCards = new ArrayList<String>();

while(listIterator.hasNext()) {
    pickedCards.add(listIterator.next());
}

String c1 = pickedCards.get(0);
String c2 = pickedCards.get(1);
String c3 = pickedCards.get(2);

c1,c2和c3的值现在类似于"card2""card1""card3"

相关问题