【问题标题】:IndexOutOfBoundsException while adding to a list in an arraylist添加到数组列表中的列表时出现 IndexOutOfBoundsException
【发布时间】:2015-07-20 22:25:57
【问题描述】:

我正在制作一个程序,它必须根据前两个字母对每个英文单词进行排序。每组两个字母都有自己的列表,我必须将单词添加到其中,因此我总共有 676 个列表。我尝试制作一个列表的 ArrayList 来做到这一点:

public static List<List<String>> englishWordList = new ArrayList<List<String>>(673);

现在,当我尝试将元素添加到其中一个列表时,我得到了一个 IndexOutOfBoundsException

    private static void letterSort(String s){
    //Sorts the words by the first two letters and places in the appropriate list.
    String letterGet = s.substring(0,2);
    for(int i = 0; i < 676; i++){
        if(letterGet.equals(letterCombos[i])){
            Debug(s);
            Debug(letterGet);
            try{
                englishWordList.get(i).add(s); \\IndexOutOfBoundsException here
            }catch(Exception e){
                e.printStackTrace();
                System.exit(0);
            }
        }
    }

非常感谢任何有关解决此问题的帮助,如果需要更多信息,我将非常乐意添加。

【问题讨论】:

  • 可能是另一个问题,但是您已经声明了一个包含 673 个对象的列表,但您正在迭代到 676 个,因此您试图访问 3 个不存在的对象。我不会迭代到 676,而是改为 englishWordList.size()

标签: java list arraylist indexoutofboundsexception


【解决方案1】:

您只初始化了englishWordList,但没有向其中添加任何内容。因此englishWordList 为空,任何get(int) 调用都会抛出IndexOutOfBoundsException

您可以通过以下方式将其填充为空的Lists(另请注意,您将初始容量设置为 673 而不是 676):

public static List<List<String>> englishWordList = new ArrayList<List<String>>(676);
static {
    for (int i = 0; i < 676; i++) {
        englishWordList.add(new ArrayList<String>());
    }
}

【讨论】:

    猜你喜欢
    • 2017-01-13
    • 2018-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-25
    • 2014-03-13
    • 1970-01-01
    相关资源
    最近更新 更多