Arraylist java.lang.IndexOutOfBoundsException:索引 3 超出长度 3 错误

编程入门 行业动态 更新时间:2024-10-26 22:16:23
本文介绍了Arraylist java.lang.IndexOutOfBoundsException:索引 3 超出长度 3 错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我创建了一个方法,它采用字符串和整数的 Arraylist.它将删除所有长度小于给定整数的字符串.

I created a method which takes an Arraylist of string and an integer. It's going to remove all string whose length is less than the given integer.

例如:

Arraylist = [abcde"、aabb"、aaabbb"、abc"、ab"]

Arraylist = ["abcde", "aabb", "aaabbb", "abc", "ab"]

整数 = 4

所以新的 Arraylist 应该是:[abcde", aabb", aaabbb"]

So the new Arraylist should be: ["abcde", "aabb", "aaabbb"]

但我收到此错误消息:

线程main"中的异常java.lang.IndexOutOfBoundsException: 索引 3 超出长度 3 的边界

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index 3 out of bounds for length 3

这是我的代码:

public static void main(String[] args){
        ArrayList<String> newArrayList = new ArrayList<>();
        newArrayList.add("string1");
        newArrayList.add("string2");
        newArrayList.add("rem");
        newArrayList.add("dontremove");
        removeElement(newArrayList, 4); // new arraylist must be = [string1, string2, dontremove]
    }


    public static void removeElement(ArrayList<String> arraylist, int inputLen){
        int arrayLen = arraylist.size();
        for(int i=0; i<arrayLen; i++){
            if(arraylist.get(i).length() < inputLen){
                arraylist.remove(i);
                i--;
            }
        }
        System.out.println("New Arraylist: " + arraylist);
    }

这段代码有什么问题?

推荐答案

当你移除元素时,数组的长度应该改变.arrayLen 变量存储数组的长度,但在数组长度缩小时不会改变.要更改它,您应该能够将 arrayLen 替换为 arrayList.size(),这将在您删除元素时更改

The length of the array should change when you remove elements. The arrayLen variable stores the length of the array, but doesn't change when the array's length shrinks. To change it, you should be able to just replace arrayLen with arrayList.size(), which will change when your remove elements

这篇关于Arraylist java.lang.IndexOutOfBoundsException:索引 3 超出长度 3 错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

更多推荐

[db:关键词]

本文发布于:2023-04-16 07:11:42,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/881963.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:长度   索引   错误   java   Arraylist

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!