有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

ArrayList<class>的Java remove()函数(我需要帮助)

如何删除以前在ArrayList中添加的元素<&燃气轮机;我是这样创建的:

public static ArrayList<Product> P = new ArraList<Product>(); 

我使用的方法是:

public void removeProduct(Product p) {
    P.remove(p); // this way, did not solve the problem 
} 

//我做了(添加了该方法),效果很好,一切都很好,希望有人能帮我找到答案,谢谢:)

public void deleteProduct(String ID) {
    System.out.println("Enter product id to delete: ");
    ID = input.next();
    for(Product m : s.P) {
        if(ID.equals(m.getID())) {
            s.P.remove(ID);
        }
        else {
            System.out.println("ID is not exist");
        }
    }
}

//及

public void removeProductToCart(Product p) {
    viewShoppingCart();
    System.out.println("Enter product id to remove it: ");
    String ID = input.next();
    for(Product r : s.P) {
        if(ID.equals(r.getID())) {
            s.P.remove(p);
        }
        else {
            System.out.println("ID is not exist");
        }
    }
}

共 (2) 个答案

  1. # 1 楼答案

    问题2:

    1. s、 P是产品列表,而不是字符串,因此调用remove(String)不起作用
    2. 删除for each循环中的元素将抛出ConcurrentModificationException

    可能的解决办法:

    public void removeProductToCart(Product p) {
        viewShoppingCart();
        System.out.println("Enter product id to remove it: ");
        String ID = input.next();
        Product toRemove = null;
        for(Product r : s.P) {
            if(ID.equals(r.getID())) {
                toRemove = r;
                break;
            }
        }
        if(toRemove == null) {
            System.out.println("ID is not exist");
        }
        else {
            s.P.remove(toRemove);
        }
    }
    


    如果传递的参数是需要删除的产品,则可以简化此操作

    相同的逻辑可应用于第一个功能:

    public void deleteProduct(String ID) {
        System.out.println("Enter product id to delete: ");
        ID = input.next();
        Product toRemove = null;
        for(Product r : s.P) {
            if(ID.equals(r.getID())) {
                toRemove = r;
                break;
            }
        }
        if(toRemove == null) {
            System.out.println("ID is not exist");
        }
        else {
            s.P.remove(toRemove);
        }
    }
    

    注意:方法参数目前没有任何用途。为什么不使用它们而不是循环查找产品

  2. # 2 楼答案

    您需要使用迭代器,否则将得到java.util.ConcurrentModificationException。抛出异常,因为您正在列表上执行两个操作:迭代删除

    所以,你需要这样的东西:

    for (Iterator<Book> it = s.P.listIterator(); it.hasNext(); ) {
        Product r = it.next();
        if(ID.equals(r.getID())) {
            it.remove(r);
        }
    }
    

    因为根本原因是执行2个操作,所以还有另一种方法- 只需在迭代的每个步骤上创建列表的副本:

    for(Product m : new ArrayList<>(s.P)) {
        if(ID.equals(m.getID())) {
            s.P.remove(m);
        }
    }
    

    注意:出于性能考虑(每一步的二次内存使用和线性删除),我不推荐最后一种方法。我给出这个例子只是为了强调java的根本原因。util。将引发ConcurrentModificationException