0

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.

8
  • 1
    Which line throws the exception? My guess would be the if statement because leters is null, and not the array. Please read this: How to create a Minimal, Complete, and Verifiable example. Commented Nov 8, 2016 at 22:17
  • 2
    Also, why 25? There are 26 letters in the base alphabet. Many languages have more than that. Commented Nov 8, 2016 at 22:19
  • 1
    Unable to reproduce: IDEONE. As you may also notice, letter Z is missing since you only have 25 letters. Commented Nov 8, 2016 at 22:23
  • 1
    That's impossible with the code you showed. Commented Nov 8, 2016 at 22:43
  • 1
    So you're using the cyrillic alphabet, but only the first 25? АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШ Commented Nov 8, 2016 at 23:03

1 Answer 1

4

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); 
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.