2013-02-17 79 views
0

我正尝试在Java中创建一个内容管理系统,我在其中插入章节名称并在章节内创建节。我已经使用了以下数据结构:现在在HashMap中StringList的ArrayList中添加动态内容

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

,插入,我使用下面的代码:

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

的问题是我得到的最后一个元素,该元素的其余部分是被覆盖。但是,我不能在章节中使用固定的ArrayList。我必须从GUI中插入字符串运行时。我如何克服这个问题?

+0

你对所有的键使用'Chapter'? – 2013-02-17 16:09:45

回答

1

是的,你创建一个新的 arraylist每次。你需要检索现有的,如果有的话,并添加到它。喜欢的东西:

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

你必须得到含有从地图第一小节中的ArrayList:

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

然后创建它只有在它不存在:

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

然后在该部分的末尾添加您的文字:

section.add(textField.getText()); 

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