Search code examples
javaarraylistindexoutofboundsexception

How to properly populate an ArrayList of type ArrayList<String>?


I'm an APCSA student and am trying to answer a question in the textbook. Basically, given an ArrayList of different words, I need to create and return an ArrayList of type ArrayList with 26 "buckets", each containing all the words that start with "a", then "b", and so on, until the intial ArrayList is completely sorted by the first letter of the words. The method can only parse the initial ArrayList once and cannot alter it. As my code stands now, I keep getting an out of bounds error. If someone can point me in the right direction, that'd be awesome, thanks. This is what I have currently, and I have no idea if it's even close to right:

public static ArrayList<ArrayList<String>> sortWords(ArrayList<String> words)
{
    ArrayList<ArrayList<String>> buckets = new ArrayList<ArrayList<String>>(26);
    String letters = "abcdefghijklmnopqrstuvwxyz";


    for(int i = 0; i < 26; i++)
    {
        //keeps track of current letter in letters
        int let = 0;

        for(int word = 0; word < words.size(); word++)
        {
            //if first letter of current word equals letter for current bucket
            if(letters.substring(let,let+1).compareToIgnoreCase(words.get(word).substring(0, 1)) == 0)
                buckets.get(i).add(words.get(word));
        }
        let++;
    }

    return buckets;
}

Solution

  • The '26' there just says that the arraylist is optimized to handle 26 elements. It is still an empty arraylist with zero elements in it. At the top of your for (26) loop, try adding buckets.add(new ArrayList<>());.

    Also, you're not doing what the question asks; you're looping the input 26 times, the question as asked wants you to loop that only once. (and as it is homework, it wouldn't help your education if I just caught this fish for you).