首页 > 解决方案 > 修复 ArrayList 中的 IndexOutOfBounds 异常

问题描述

我正在尝试制作一个将所有单词存储在一个句子中的 String ArrayList。目前,我正试图通过查找空间的索引并将其存储在数组中来实现这一点。空格的数组列表有效,但是单词的数组列表无效。字符串数组列表的值是两个空格索引之间的子字符串。请帮忙。

for(int x = 0; x < spaces.size(); x++) {
    words.add(post.substring(spaces.get(x) + 1, spaces.get(x + 1)));
}

标签: javaarraylistsubstringindexoutofboundsexception

解决方案


什么时候xsize()-1,然后你会调用x+1which will equal to size()which is not a valid index

由于您正在查看一个索引,因此仅循环直到小于size()-1

for(int x = 0; x < spaces.size()-1; x++) {
    words.add(post.substring(spaces.get(x) + 1, spaces.get(x + 1)));
}

推荐阅读