【问题标题】:Iterating through an ArrayList and also dynamically removing and adding elements at a specific index遍历 ArrayList 并在特定索引处动态删除和添加元素
【发布时间】:2018-04-21 08:37:04
【问题描述】:

我正在尝试找到我的问题的答案,但似乎没有什么是具体的,但如果这是重复的,我很抱歉(我也是 java 新手)。

假设我有一个 ArrayList,其中包含:

[I, love, computer, science, and, applied, mathematics]

我想更改数组以便

[I, love, computer science, and, applied mathematics] 

基本上,我想删除“计算机”和“科学”,并在该特定位置插入“计算机科学”。然后迭代器必须继续从“and”开始,并为“applied”和“mathematics”做同样的事情。

我正在考虑使用带有索引 i 的 forloop,但我了解到在不使用迭代器的情况下从列表中动态删除是不好的。我也可以使用 LinkedList,但我不确定索引会如何变化。

我真的很感激一些建议!谢谢!

【问题讨论】:

    标签: java arraylist iterator nlp


    【解决方案1】:

    如果列表中的那些对象是字符串,则无需对集合执行 for 循环,只需 remove 他们添加新元素

    List<String> xyzList = new ArrayList<>(
            Arrays.asList("I", "love", "computer", "science", "and", "applied", "mathematics"));
    System.out.println(xyzList);
    int index = xyzList.indexOf("computer");
    xyzList.remove("computer");
    xyzList.remove("science");
    xyzList.add(index, "computer science");
    System.out.println(xyzList);
    

    但是,嘿...要小心,想想会发生什么是那些元素不在列表中.... :)

    【讨论】:

    • hmmm...也许我应该澄清一下 - 我真的不知道这个数组列表中的内容更具体。我将遍历以查看三个索引组合是否会构成一个实际单词,如果是,则从这些索引中删除这 3 个字符串,插入新单词,然后继续向下移动列表
    猜你喜欢
    • 1970-01-01
    • 2015-05-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-19
    • 1970-01-01
    • 2021-10-02
    相关资源
    最近更新 更多