【发布时间】:2016-04-12 21:30:09
【问题描述】:
这是Data.ListGroupedProducts的声明
public static HashMap<String, HashMap<String, WrapperProduct>> ListGroupedProducts = new HashMap<>();
我这样做的原因是用新的/更新的对象替换集合深处的对象。我在尝试 get HashMap 中需要的集合时继续获得 null。
这是我的调试截图,鼠标悬停在Data.ListGroupedProducts。
红色箭头是我试图达到的......不可能用for循环迭代它吗?
更新
感谢Boann 的回答,我能够解决这个问题。这是完整的方法,以防有人犯我在尝试使用 for 循环迭代 KeySet 时犯的同样错误!
//Product coming in, has the latest updates and this will be used
//to update the product deep in Data.ListGroupedProducts.
public boolean UpdateListGroupProducts(ManifestProduct product) {
for(int a=0; a < Data.SelectedInvoice.size(); a++){
String invoiceNumber = Data.SelectedInvoice.get(a).ID;
if(Data.ListGroupedProducts.containsKey(invoiceNumber)){
//Iterate over each key using a keyset, we will then use the key on the for-loop
//to retrieve the inner object and manipulate it as needed.
for(String key: Data.ListGroupedProducts.get(invoiceNumber).keySet()){
for(int x=0; x < Data.ListGroupedProducts.get(invoiceNumber).get(key).ProductList.size(); x++){
String productID = Data.ListGroupedProducts.get(invoiceNumber).get(key).ProductList.get(x).ID;
String productItemID = Data.ListGroupedProducts.get(invoiceNumber).get(key).ProductList.get(x).ITEMID;
if(product.ID.equals(productID) && product.ITEMID.equals(productItemID)){
//Use ArrayList's set method to replace a position in the array with a new instance.
Data.ListGroupedProducts.get(invoiceNumber).get(key).ProductList.set(x, product);
return true;
}
}//Inner For
}//Outer For
}
}
return false;
}
【问题讨论】:
-
你能把这个减少到minimal reproducible example吗?请遵循 Java 命名约定。如果您要重用
Data.ListGroupedProducts.get(invoiceNumber)的值,请将其提取到一个短名称变量并重用它。使代码更具可读性。 -
a <= Data.SelectedInvoice.size()-1通常写成a < Data.SelectedInvoice.size()。 -
这没有多大意义。你打电话给
containsKeyData.SelectedInvoice.get(a).ID,然后你打电话给getData.SelectedInvoice.get(a).ID.toString()。他们不应该是一样的吗? -
@PaulBoddington Java 新手--containsKey 返回值?以为我只是在检查,这就是为什么我后来做了
get.. -
containsKey检查键是否在映射中并返回true或false。这与您应该传递给get的内容相同。您是否尝试将.toString()添加到您传递给containsKey()的内容中?