简体   繁体   中英

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. I tried making an ArrayList of Lists to do this:

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

    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. Therefore englishWordList is empty and any get(int) call will throw an IndexOutOfBoundsException .

You can fill it with empty List s the following way (also note that you set initial capacity to 673 instead of 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>());
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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