I have problem with filling a Map
in Java, I think this is simple, but I can't resolve this.
Let's look at this:
Map<Integer, HashMap<String, String>> lineArrayData = new HashMap<Integer, HashMap<String, String>>();
HashMap<String, String> map = new HashMap<String, String>();
String singleData[];
int lineCounter = 0;
for ( String line : this.lines )
{
singleData = line.split("\\|\\|");
map.put("type", singleData[0]);
map.put("text", singleData[1]);
map.put("page", singleData[2]);
map.put("x", singleData[3]);
map.put("y", singleData[4]);
lineArrayData.put(lineCounter, map);
lineCounter++;
}
System.out.println(lineArrayData);
I have input
barcode||testowy test||1||100||100
text||texttstdasd||2||500||300
and my output is:
{0={text=texttstdasd, page=2, type=text, y=300, x=500}, 1={text=texttstdasd, page=2, type=text, y=300, x=500}}
what have I done wrong?
Move the following line inside the loop:
HashMap<String, String> map = new HashMap<String, String>();
Otherwise every iteration modifies the same inner map. The end result is that the outer map contains multiple references to the same inner map.
Here is the corrected version:
for ( String line : this.lines )
{
HashMap<String, String> map = new HashMap<String, String>();
singleData = line.split("\\|\\|");
...