示例代码:
主程序:
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++;
}
}
}
示例输出:
{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}
查看示例输出:
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.
问题:
我实际观察到了真实程序中第3行到第6行的行为。我尝试使用一个小程序进行复制并且成功,但它在此过程中创建了更多问题。