Example Code :
Main Program :
package com.company.reference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Reference {
public static void main (String arga[]) {
List<Map<String,Data>> listOfMaps = new ArrayList<Map<String, Data>>();
Map<String, Data> m0 = new HashMap<String, Data>();
m0.put("userLines", new Data("amy", "strachan"));
Map<String, Data> m1 = new HashMap<String, Data>();
m1.put("userLines", new Data("amy", "strachan"));
listOfMaps.add(m0); listOfMaps.add(m1);
for (Map<String,Data> m3 : listOfMaps) {
System.out.println(m3);
}
List<Document> docs = new ArrayList<Document>();
for (int i = 0; i < 2; i++) {
Line line = new Line();
line.setDayOfWeek(DayOfWeek.MON);
line.setActivity("1");
Map<enumUser, Line> m = new HashMap<enumUser, Line>();
m.put(enumUser.USER, line);
Document doc = new Document();
int docId = i;
doc.setId(docId);
doc.setUserLines(m);
docs.add(doc);
}
int cnt = 0;
for (Document document : docs) {
System.out.println(document.getUserLines());
document.getUserLines().get(enumUser.USER).setActivity("foo" + cnt);
System.out.println(document.getUserLines());
cnt++;
}
}
}
Example Output :
{a=com.company.reference.Data@30c3bb57}
{a=com.company.reference.Data@4402083d}
{U=com.company.reference.B@bb56a086}
{U=com.company.reference.B@bb86ac7f}
{U=com.company.reference.B@bb56a086}
{U=com.company.reference.B@bb86ac80}
Looking at the example output :
a) Line 1 and Line 2 have different references.
b) Line 3 and Line 5 have the same reference, Line 4 and Line 6 have different references.
Question :
- Why do Line 3 and Line 5 have the same reference? Shouldnt they essentially emulate the behavior of Line 1 and Line 2.
- How did the Java runtime, separate the references in Line 4 and Line 6. That is, if there was an optimization done, how come the runtime was able to separate them once the internal values were different.
- If the Java runtime optimized Line 3 and Line 5, why did it not do the same for Line 1 and Line 2.
I actually observed the behavior in Lines 3 to Lines 6 in a real program. I attempted to replicate using a small program and was successful, but it created more questions in the process.