簡體   English   中英

如何將每個哈希圖添加到arrayList

[英]How to add each hashmap to a arrayList

final ArrayList<HashMap<String, String>> actualList = new ArrayList<HashMap<String, String>>();

for (Response response : responseList) {
           if (responseList != null) {
               resultsMap.put("a", response.getResult());
               resultsMap.put("b",  response.getOriginalUrl())

              actualList.add(resultsMap);
}

這不會添加到hashList到arrayList

在給定的代碼中

  1. 您沒有在循環中初始化哈希圖,因此a和b的值將在每次responseList迭代的哈希圖中被覆蓋。
  2. 在循環中不使用檢查responseList null的用途,因此我將其刪除。

嘗試這個,

final ArrayList<HashMap<String, String>> actualList = new ArrayList<HashMap<String, String>>();
HashMap<String, String> resultsMap = null;
for (Response response : responseList) {
            resultsMap = new HashMap<>();
               resultsMap.put("a", response.getResult());
               resultsMap.put("b",  response.getOriginalUrl())

              actualList.add(resultsMap);
}
final ArrayList<HashMap<String,String>> actualList = new ArrayList<HashMap<String, String>>();
for (Response response : responseList) { 
    if (response != null){
        Map resultsMap = new HashMap<String, String>();
        resultsMap.put("a", response.getResult()); 
        resultsMap.put("b", response.getOriginalUrl()) 
        actualList.add(resultsMap);
    }
}
final ArrayList<HashMap<String, String>> actualList = new ArrayList<HashMap<String, String>>();
if (responseList != null) {
    for (Response response : responseList) {
      HashMap<String, String> map=new HashMap<>();
      map.put("a", response.getResult());
      map.put("b",  response.getOriginalUrl())
      actualList.add(map);
    }
}

您應該為循環的每次迭代創建一個新的HashMap實例。

除此之外,也許您打算檢查循環內的response是否不為空,因為responseList不能為空。

final ArrayList<HashMap<String, String>> actualList = new ArrayList<HashMap<String, String>>();

for (Response response : responseList) {
    HashMap<String, String> resultsMap = new HashMap<String, String> ();
    if (response != null) {
        resultsMap.put("a", response.getResult());
        resultsMap.put("b",  response.getOriginalUrl())

        actualList.add(resultsMap);
    }
}

您可以這樣寫:

final ArrayList<HashMap<String, String>> actualList = new ArrayList<HashMap<String, String>>();

for (Response response : responseList) {
  HashMap<String,String>resultMap = new HashMap<String,String>();
           if (responseList != null) {
               resultsMap.put("a", response.getResult());
               resultsMap.put("b",  response.getOriginalUrl())
                }
      actualList.add(resultMap);        
}

暫無
暫無

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

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