gpt4 book ai didi

java - 使用 ListIterator 从列表中删除项目

转载 作者:行者123 更新时间:2023-12-02 07:34:13 26 4
gpt4 key购买 nike

代码:

 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()));然后从列表中删除所选的卡。换句话说,我希望字符串 c1 从列表中随机选择,然后将其选择的卡从列表中删除,但保留在值 c1 中。我想我当前的代码不起作用,因为当我删除它所选择的内容时,它也会从字符串 c1 中删除该卡。我不知道如何正确执行此操作。

最佳答案

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

This call can only be made once per call to next or previous. It can be made only if ListIterator.add has not been called after the last call to next or previous.

这意味着,无需调用 next()在迭代器上获取第一个元素,您仍然处于非法状态。

无论如何,根本不需要使用迭代器。 remove(int index)方法来自List<E>就可以了:

String c1 = list.remove(rand.nextInt(list.size));

关于java - 使用 ListIterator 从列表中删除项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12487915/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com