0

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?

1
  • Are you using Chapter for all the keys? Commented Feb 17, 2013 at 16:09

2 Answers 2

1

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

Comments

1

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.

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.