簡體   English   中英

如何理解ArrayList <Map<String,Object> &gt; 在多層循環中,ArrayList <Map<String,Object> &gt; 內容一樣嗎?

[英]How to understand the ArrayList<Map<String,Object>> in multi-layer loop, the ArrayList<Map<String,Object>> contents are the same?

當我在多層循環中使用 ArrayList<Map<String,Object>> 時, ArrayList<Map<String,Object>> 很奇怪。

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;
    }
}

打印值為: 在此處輸入圖片說明

所以我想問的是,當我在多層循環中使用 ArrayList<Map<String, Object>> 時,為什么 ArrayList<Map<String, Object>> 內容是一樣的。

這是因為在第一個循環中您繼續使用相同的臨時變量。 您基本上在 resList 中保存了 3 次相同的臨時參考。

如果在第二個示例中將 temp 放在 for 循環之外,您將獲得完全相同的結果:

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);

如果您將第一個示例中的臨時對象移動到第二個 for 循環內,您將獲得與第二個相同的結果。 添加一個System.out.println(resList); 在兩個 for 循環中以更好地了解正在發生的事情。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM