Java 在HashMap中字符串的ArrayList中添加动态内容

Java 在HashMap中字符串的ArrayList中添加动态内容,java,arraylist,hashmap,Java,Arraylist,Hashmap,我试图用Java创建一个内容管理系统,在其中插入章节名称并在章节内创建章节。我使用了以下数据结构: static ArrayList<String> chapters = new ArrayList<String>(); static Map<String,ArrayList<String>> subsections = new HashMap<String,ArrayList<String>>(); static Arr

我试图用Java创建一个内容管理系统,在其中插入章节名称并在章节内创建章节。我使用了以下数据结构:

static ArrayList<String> chapters = new ArrayList<String>();
static Map<String,ArrayList<String>> subsections = new HashMap<String,ArrayList<String>>();
static ArrayList chapters=new ArrayList();
静态映射子节=新HashMap();
现在,对于插入,我使用以下代码:

ArrayList<String> secname = new ArrayList<String>();
secname.add(textField.getText());
MyClass.subsections.put("Chapter", secname);
ArrayList secname=new ArrayList();
添加(textField.getText());
MyClass.subsections.put(“章”,secname);
问题是我得到的是最后一个元素,其余元素被覆盖。但是,我不能为章节使用固定的ArrayList。我必须在运行时和GUI中插入字符串。如何克服此问题?

是的,每次都会创建一个新的空arraylist。您需要检索现有的,如果有的话,并添加到它。比如:

List<String> list = MyClass.subsections.get("Chapter");
if (list == null) {
    list = new ArrayList<String> ();
    MyClass.subsections.put("Chapter", list);
}
list.add(textField.getText());
List List=MyClass.subsections.get(“章节”);
if(list==null){
list=newarraylist();
MyClass.subsections.put(“章节”,列表);
}
add(textField.getText());

您必须首先从地图中获取包含子部分的ArrayList:

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

每次调用“put”时,代码都会替换索引“Chapter”处的ArrayList,这可能会删除此索引处以前保存的数据

您是否对所有钥匙使用
章节
if (section == null) {
    ArrayList<String> section = new ArrayList<String>();
    subsections.put("Chapter", section);
}
section.add(textField.getText());