Jyotiska
Jyotiska

Reputation: 255

Add dynamic content in ArrayList of String in a HashMap

I am trying to create a content management system in Java, where I insert chapter names and create sections inside a chapter. I have used the following data structures:

static ArrayList<String> chapters = new ArrayList<String>();
static Map<String,ArrayList<String>> subsections = new HashMap<String,ArrayList<String>>();

Now, for insertion, I am using the following code:

ArrayList<String> secname = new ArrayList<String>();
secname.add(textField.getText());
MyClass.subsections.put("Chapter", secname);

The problem is I am getting the last element, the rest of the elements are getting overwritten. But, I cannot use a fixed ArrayList for the chapters. I have to insert strings runtime and from the GUI. How do I overcome this problem?

Upvotes: 0

Views: 678

Answers (2)

Thibault D.
Thibault D.

Reputation: 10004

You have to get the ArrayList containing the subsections from the map first:

ArrayList<String> section = subsections.get("Chapter");

Then create it only if it doesn't exist:

if (section == null) {
    ArrayList<String> section = new ArrayList<String>();
    subsections.put("Chapter", section);
}

Then append your text at the end of the section:

section.add(textField.getText());

Your code does replace the ArrayList at index "Chapter" every time you call "put", potentially removing the previous saved data at this index.

Upvotes: 1

assylias
assylias

Reputation: 328913

Yes you create a new empty arraylist every time. You need to retrieve the existing one, if any, and add to it. Something like:

List<String> list = MyClass.subsections.get("Chapter");
if (list == null) {
    list = new ArrayList<String> ();
    MyClass.subsections.put("Chapter", list);
}
list.add(textField.getText());

Upvotes: 1

Related Questions