2013-02-17 81 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,可能會刪除此索引處先前保存的數據。