gpt4 book ai didi

java - 无法从数组列表中删除 HashMap

转载 作者:行者123 更新时间:2023-12-02 05:47:24 25 4
gpt4 key购买 nike

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个属性(包括零件编号)的 HashMap 。删除项目还包含4个项目,包括零件编号,正如我在上面的示例中提到的那样。所以我需要从Wrapper中删除 HashMap 在删除项目 HashMap 中具有相同部分的实例。但它不起作用

最佳答案

您正在扩展 ArrayList(您永远不应该这样做),并违反了其契约。

如果给定对象是 HashMap 并且恰好包含与列表中另一个映射相同的“part_no”键值,则可以通过声明列表包含给定对象来重写 contains()。但你不能重写remove()。并且remove()继续使用ArrayList的方法,该方法删除列表中与作为参数传递的对象等于的元素。

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

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

我怀疑您在使用 map 时应该很好地定义自己的类广告,但这并没有太大变化。

这是您应该拥有的类的框架。您应该根据以上指示自行弄清楚实现方式:

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

关于java - 无法从数组列表中删除 HashMap ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23927054/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com