java—添加新的键值对将在hashmap中替换其他键的值

2g32fytz  于 2021-06-29  发布在  Java
关注(0)|答案(1)|浏览(329)

所以,我有一个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
06odsfpq

06odsfpq1#

你的价值观 MapList 其元素与 List 退回人 getResourceList() . 事实上,你正在创建一个副本 List (两次),不会改变这一点。
如果每次呼叫 getResourceList() 返回一个 List 包含相同的示例,在 Map 将与不同的 List 包含相同示例的。

相关问题