Reputation: 184
I'm trying to make an array of ArrayLists of Strings in java because I need a list of words for every letter of alphabet. I'm doing in in this way:
ArrayList<String>[] letters = new ArrayList[32];
But I'm getting a NullPointerException when I try to add something to my list.
while ((line = bufferedReader.readLine()) != null) {
letter = (int)line.charAt(0) - 1040;
if (letters[letter] == null) {
letters[letter] = new ArrayList<>();
}
letters[letter].add(line);
}
I also tried to create it like that
ArrayList<String>[] leters = (ArrayList<String>[])new ArrayList[32];
But it didn't changed the situation. Please help me to solve my problem.
Upvotes: 0
Views: 281
Reputation: 23503
I would use a hash map:
HashMap<Character, ArrayList<String>> letters = new HashMap<Character, ArrayList<String>>();
Then you can add words by doing:
ArrayList<String> words = new ArrayList<String>();
words.add(word);
letters.put("A", words);
Upvotes: 4