I was wondering how to properly (or even if you can) add data to a HashMap
like an ArrayList
?
So I have a function, which checks the entered string for commas and separates the values, adds them into an ArrayList
and then stores the ArrayList
keyed against the name of the field they were entering data to:
ArrayList<String> dataList = new ArrayList<>();
Map<String, ArrayList<String>> dataMap = new HashMap<String, ArrayList<String>>();
String[] parts;
public void CheckForMultipleEntries(String field, String data){
dataList.clear();
if(data.contains(",")){
data.replace("", "");
parts = data.split(",");
for(String part : parts){
dataList.add(part);
}
dataMap.put(field, dataList);
}
System.out.println(dataMap);
System.out.println(dataMap.get("test"));
}
However say first for "Header"
I enter "test1, test2, test3"
- this will enter & output correctly (as: {Header=[test1, test2, test3]}
) but if for the next value I then enter, say, "Body"
"test4, test5, test6"
then when I output the map I get {Header=[test4, test5, test6], Body=[test4, test5, test6]}
.
Why is it overwriting the values, but not the keys? And how do I fix it?
Thanks for any help!