【问题标题】:How do I stop an item frombeing added to Object ArrayList如何停止将项目添加到 Object ArrayList
【发布时间】:2020-07-07 00:33:40
【问题描述】:
     HashMap<String, Object> hashMap = new HashMap<String, Object>();
                hashMap.put("id", maxRowId);
                hashMap.put("item", item_name);
                hashMap.put("price", price);
                hashMap.put("quantity", quantity);
                hashMap.put("total", total);
                //customItemArrayList.add(hashMap);
               // int id = Integer.parseInt(customItemArrayList.get(position).get("id").toString());

                for(int i = 0; i < customItemArrayList.size(); i++)
                {
                    //System.out.println(namesList.get(i));
                    String name = customItemArrayList.get(i).get("item").toString();
                    if (name.equals(item_name)){
                        Toast.makeText(getContext(), "It exists",Toast.LENGTH_LONG).show();
                        i = customItemArrayList.size();
                    } else {
                        customItemArrayList.add(hashMap);
                        //i = customItemArrayList.size();
                    }
                }

                maxRowId++;

我有一个带有哈希图的对象 ArrayList。在添加项目之前,我会检查是否已存在具有相似名称的项目。如果存在,则不应再次添加。上面的代码确实表明该项目存在,但是,它继续添加该项目。它可能有什么问题?

【问题讨论】:

  • 如果名称不存在,您要添加整个 hashMap 吗?
  • 是的,每个条目都是一个hashMap

标签: java android arrays hashmap


【解决方案1】:

当您找到具有不同名称的项目时,您正在添加新项目。假设您要添加一个名称为“bernard”的项目,而您的列表中有名称为“alice”和“bernard”的项目:新项目被添加是因为“alice”不是“bernard”。

要解决此问题,请添加一个布尔变量,告诉您是否找到了匹配项。最初它设置为假。如果找到匹配项,则将其更改为 true。之后,您检查是否找到匹配项,如果没有,则仅添加新项目。

    boolean exists = false;
    for (int i = 0; i < customItemArrayList.size(); i++) {
        //System.out.println(namesList.get(i));
        String name = customItemArrayList.get(i).get("item").toString();
        if (name.equals(item_name)) {
            exists = true;
            break;
        }
    }

    if (!exists) {
        customItemArrayList.add(hashMap);
        //i = customItemArrayList.size();
    }

【讨论】:

    【解决方案2】:

    问题是您正在遍历整个集合并检查是否存在条目。在每次相等检查中,您要比较的条目可能不是相等的条目,因此它通过了检查。您需要先检查所有条目,然后如果没有找到,请添加。

    【讨论】:

    • 我该怎么做?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-26
    • 2016-05-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-22
    相关资源
    最近更新 更多