如何删除之前在 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 个问题:
- s.P 是产品列表,而不是字符串,因此调用 remove(String( 不起作用。
- 删除 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);
}
}
注意:方法参数当前没有任何用途。为什么不使用它们而不是循环查找产品?
你需要使用迭代器,否则你会得到java.util.ConcurrentModificationException。引发异常,因为您正在对列表执行 2 个操作:迭代和删除。
所以,你需要这样的东西:
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被抛出的根本原因。