繁体   English   中英

添加到arraylist中的列表时出现IndexOutOfBoundsException

[英]IndexOutOfBoundsException while adding to a list in an arraylist

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

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);
            }
        }
    }

修复此问题的任何帮助将不胜感激,如果需要更多信息,我将非常乐意添加。

您仅初始化englishWordList ,但未对其添加任何内容。 因此englishWordList为空,任何get(int)调用都将抛出IndexOutOfBoundsException

您可以通过以下方式用空List填充它(还要注意,您将初始容量设置为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>());
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM