无法从数组列表中删除哈希映射

时间:2014-05-29 06:26:33

标签: java

public class PurchaseOrderWrapper extends ArrayList<HashMap<String, String>> {

        public boolean contains(Object o) {
            HashMap<String, String> ob = (HashMap<String, String>) o;
            for (HashMap<String, String> map : this) {
                Log.i("kasun",ob.get("part_no")+" "+ map.get("part_no")+" = "+Boolean.toString(ob.get("part_no").equalsIgnoreCase(map.get("part_no"))));
                 if(ob.get("part_no").equalsIgnoreCase(map.get("part_no"))){
                     return true;
                 }
            }
        return false;
    }
}

if (wrapper.contains(removitems)){      
    wrapper.remove(removitems);     
} 

Wrapper是PurchaseOrderWrapper类的一个实例。它包含带有5个属性的哈希映射,包括部分no.remove项目还包含4个项目,包括部分no,就像我在上面的例子中提到的那样。所以我需要从Wrapper中删除hashmap删除项目哈希映射中具有相同部分no的实例。但它不起作用

1 个答案:

答案 0 :(得分:2)

你正在扩展ArrayList(你永远不应该这样做),并且违反合同。

如果此列表包含给定对象(如果此对象是HashMap)并且恰好包含与“list_no”键相同的值(如列表中的另一个映射),则覆盖contains()。但是你不要覆盖remove()。 remove()继续使用ArrayList的方法,该方法将列表中等于的元素移除到作为参数传递的对象。

不要扩展集合类。相反,将它们包装在您自己的类中。

要实现remove方法,您可能必须遍历列表,在列表中找到与作为参数传递的映射具有相同“part_no”键值的映射,并从中删除该映射。列表。

我怀疑你是在使用地图,你应该很好地定义自己的类广告,但这并没有太大的改变。

这是你应该拥有的课程的骨架。您应该根据上述指示自行确定实施情况:

public class PurchaseOrderWrapper {
    private List<Map<String, String>> list = new ArrayList<>();

    public boolean containsElementWithSamePartNoAs(Map<String, String> map) {
        // iterate over the list and find if an element has the same part_no
        // as the map passed as argument
    }

    public void removeElementWithSamePartNoAs(Map<String, String> map) {
        // iterate over the list and find the element which has the same part_no
        // as the map passed as argument. Once found, remove this element from the list
    }
}