所以,我有一个hashmap<string,arraylist>,它为每个字符串存储一个arraylist。但是当我添加另一个具有arraylist新值的对时,其他键值将被替换。因此,不同键的所有值都是相同的。
public class Reports{
private ArrayList<Resource> resourceList;
private HashMap<String,ArrayList<Resource>> consolidatedAttendance = new HashMap<String,ArrayList<Resource>>();
public void readReport(String reportFile){
//initialized with resources from config file
ArrayList<Resource> repResourceList = new ArrayList<Resource>(getResourceList());
try (BufferedReader br = new BufferedReader(new FileReader(reportFile))) {
String line;
line = br.readLine(); // disregards first line (columns)
while ((line = br.readLine()) != null) {
if(line.length()==0){
break;
}
//store each resource status in resourceList
String[] values = line.split(",");
String resourceName = values[1], resourceStatus = values[2];
int resourceIndex = indexOfResource(resourceList, resourceName);
// to add validation
if(resourceIndex!=-1){
repResourceList.get(resourceIndex).setStatus(resourceStatus);
}
}
}catch(IOException e){
e.printStackTrace();
}
//get Date
String reportFilename = reportFile.substring(0, reportFile.indexOf("."));
String strDate = reportFilename.substring(reportFilename.length()-9);
consolidateRecords(strDate, new ArrayList<Resource>(repResourceList));
}
public void consolidateRecords(String strDate, ArrayList<Resource> repResourceList){
//consolidate records in hashmap
consolidatedAttendance.put(strDate, repResourceList);
// test print
for (String key: consolidatedAttendance.keySet()){
ArrayList<Resource> resources = consolidatedAttendance.get(key);
for(Resource resource: resources){
System.out.println(key+": "+resource.getNickname()+" "+resource.getEid()+" "+resource.getStatus());
}
}
}
}
因此,Map打印时的输出为:
添加的第一个键:
"21-Dec-20": John Working
"21-Dec-20": Alice Working
"21-Dec-20": Jess Working
对于第二个关键点,列表中有区别。但是,当添加第二个键(在put()方法之后)时,第一个键的值已被替换。
"21-Dec-20": John SL
"21-Dec-20": Alice Working
"21-Dec-20": Jess SL
"28-Dec-20": John SL
"28-Dec-20": Alice Working
"28-Dec-20": Jess SL
1条答案
按热度按时间06odsfpq1#
你的价值观
Map
是List
其元素与List
退回人getResourceList()
. 事实上,你正在创建一个副本List
(两次),不会改变这一点。如果每次呼叫
getResourceList()
返回一个List
包含相同的示例,在Map
将与不同的List
包含相同示例的。