You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

编写removeEvenLength方法移除偶数长度字符串时遇数组越界异常求助

Fixing IndexOutOfBoundsException in removeEvenLength Method

Hey Matthew, let's break down why you're hitting that IndexOutOfBoundsException and get your method working properly.

The Root Cause

From your code snippet, it looks like you're using the initial size of the list as your loop limit, and if you're modifying the original list (deleting elements) while iterating forward, you'll run into trouble. Here's why:

  • When you delete an element from the ArrayList, all elements after it shift left to fill the gap, which reduces the list's length.
  • But your loop keeps running up to the original size value. Eventually, you'll try to access an index that no longer exists in the now-shortened list, triggering the exception.

Solutions

Let's go through a few solid approaches to fix this, depending on whether you want to return a new list or modify the original one.

Option 1: Create a New List (Recommended, No Side Effects)

This is the safest approach—you'll collect all the strings with odd lengths into a new list, leaving the original list untouched. Your code started this way, so let's finish it properly:

public static ArrayList<String> removeEvenLength(ArrayList<String> list) {
    ArrayList<String> newLst = new ArrayList<>();
    // Use an enhanced for loop to safely iterate over the original list
    for (String str : list) {
        // Only keep strings with odd lengths
        if (str.length() % 2 != 0) {
            newLst.add(str);
        }
    }
    return newLst;
}

No index juggling here, so there's zero risk of out-of-bounds errors.

Option 2: Modify the Original List (Reverse Iteration)

If you need to alter the original list instead of creating a new one, iterate backwards from the last element to the first. This way, deleting an element doesn't affect the indices of the elements you haven't checked yet:

public static ArrayList<String> removeEvenLength(ArrayList<String> list) {
    // Start from the end of the list and move left
    for (int x = list.size() - 1; x >= 0; x--) {
        if (list.get(x).length() % 2 == 0) {
            list.remove(x);
        }
    }
    return list;
}

Option 3: Use an Iterator (Java's Safe Modification Tool)

Iterators are designed explicitly for safely modifying collections while traversing them. This is the standard Java way to handle in-place deletions:

public static ArrayList<String> removeEvenLength(ArrayList<String> list) {
    Iterator<String> iterator = list.iterator();
    while (iterator.hasNext()) {
        String str = iterator.next();
        if (str.length() % 2 == 0) {
            // Use the iterator's remove() method, not the list's!
            iterator.remove();
        }
    }
    return list;
}

Avoid calling list.remove() directly while using a regular for loop—this is what causes the index mismatch that leads to your exception.

内容的提问来源于stack exchange,提问作者Matthew

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 07:56:34