简体   繁体   English

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

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

I am making a program which has to sort every English word based on the first two letters. 我正在编写一个程序,该程序必须根据前两个字母对每个英语单词进行排序。 Each group of two letters has it's own list which I have to add the words into therefore I have 676 lists in total. 每组两个字母都有它自己的列表,我必须在其中添加单词,因此我总共有676个列表。 I tried making an ArrayList of Lists to do this: 我尝试制作一个ArrayList of List来做到这一点:

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

Now when I try to add elements to one of the lists I get this an IndexOutOfBoundsException 现在,当我尝试将元素添加到列表之一时,得到了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);
            }
        }
    }

Any help with fixing this would be very appreciated, also if any more information is needed I will be more than happy to add it. 修复此问题的任何帮助将不胜感激,如果需要更多信息,我将非常乐意添加。

You only initialized the englishWordList , but you didn't add anything to it. 您仅初始化englishWordList ,但未对其添加任何内容。 Therefore englishWordList is empty and any get(int) call will throw an IndexOutOfBoundsException . 因此englishWordList为空,任何get(int)调用都将抛出IndexOutOfBoundsException

You can fill it with empty List s the following way (also note that you set initial capacity to 673 instead of 676): 您可以通过以下方式用空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