1

when I use ArrayList<Map<String,Object>> in multi-layer loop, the ArrayList<Map<String,Object>> are weird.

import java.util.*;

public class Main {
    public static void main(String [] args){
        ArrayList<Map<String, Object>>resList=new ArrayList<>();
        ArrayList<Map<String, Object>>resList1=new ArrayList<>();
        ArrayList<String>feeNameList=feeNameList();
        for(int i=0;i<1;i++){
            Map<String, Object>temp=new HashMap<>();
            for(int j=0;j<feeNameList.size();j++){
                temp.put("feeName",feeNameList.get(j));
                System.out.println(temp);
                resList.add(temp);
            }
        }
        System.out.println(resList);

        System.out.println("------------------------------------------------");
        for(int i=0;i<feeNameList.size();i++){
            Map<String, Object>temp=new HashMap<>();
            temp.put("feeName",feeNameList.get(i));
            System.out.println(temp);
            resList1.add(temp);
        }

        System.out.println(resList1);
    }

    public static ArrayList<String>feeNameList(){
        Set<String> costNameSets=new HashSet<>();
        costNameSets.add("CIC");
        costNameSets.add("VGM申报费VGM_COST");
        costNameSets.add("延补料费");
        ArrayList<String> costNameList=new ArrayList<>();
        costNameList.addAll(costNameSets);
        return costNameList;
    }
}

the print value is: enter image description here

So What I want to ask is that when I use the ArrayList<Map<String, Object>> in a multi-layer loop, why the ArrayList<Map<String, Object>> contents are the same.

Helin
  • 65
  • 1
  • 4
  • 2
    In your first loop, you are using the same temp map, all references will point to that object. In your second, you create a separate map for each element. – RealSkeptic Nov 03 '20 at 10:21

1 Answers1

1

This is because in the first loop you keep using the same temp variable. You're basically saving the same temp reference 3 times in your resList.

You would get the exact same result if you'd put temp outside of the for loop in the second example:

System.out.println("------------------------------------------------");
// We moved temp outside of the for loop and will get the same result as the first one
Map<String, Object>temp=new HashMap<>();
for(int i=0;i<feeNameList.size();i++){
    temp.put("feeName",feeNameList.get(i));
    System.out.println(temp);
    resList1.add(temp);
}

System.out.println(resList1);

If you move the temp object in the first example inside the second for loop you'd get the same result of the second one. Add a System.out.println(resList); in both for loops to get a better understanding of what's going on.