簡體   English   中英

在HashMap中的StringList中添加動態內容

[英]Add dynamic content in ArrayList of String in a HashMap

我正在嘗試用Java創建一個內容管理系統,我在其中插入章節名稱並在章節中創建章節。 我使用了以下數據結構:

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插入字符串運行時。 我該如何克服這個問題?

是的,你每次都會創建一個新的 arraylist。 您需要檢索現有的一個,如果有的話,並添加到它。 就像是:

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

您必須首先從地圖中獲取包含子部分的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,從而可能刪除此索引處的先前保存的數據。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM