1

I have a problem to store data in this hashmap, I'm programming in Java.

My system consists of some chats, in the hash map I have to insert chats as indexes and the list of users who are connected to a specific chat, my problem is the initialization of the hashmap, as I only have to enter the chats but the arraylists are empty because there is no user connected, only I cannot understand how to do this correctly.

This is a little sample of my code:

public class Master {
   private HashMap<String, ArrayList<String>> chatBox;

   public Master() {
      chatBox = new HashMap<String, ArrayList<String>>();
   }

   public insert() {
      FileReader fr;
      BufferedReader br;
      try {
        fr = new FileReader("listChat.txt");
        br = new BufferedReader(fr);
        while(true) {
            String topic = br.readLine();
            if(topic == null)
                break;
            chatBox.put(topic, null);
        }

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } 
  }
1
  • 1
    So, what's the concrete problem? null is not an empty ArrayList. It's no ArrayList at all. An empty ArrayList is created using new ArrayList<>(). Commented Mar 18, 2019 at 9:57

1 Answer 1

2

I will suggest you to change the code that way by creating an empty ArrayList when you add a new element in the hashmap:

while(true) {
        String topic = br.readLine();
        if(topic == null)
            break;
        chatBox.put(topic, new ArrayList<String>());
    }

When you will have to update this topic with messages, you get the value for the key "topic" and add new elements in the ArrayList

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks was just that mistake, I was getting lost in a glass of water.

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.