gpt4 book ai didi

java - 从数组列表中删除

转载 作者:行者123 更新时间:2023-12-01 07:31:31 24 4
gpt4 key购买 nike

我想稍微优化一下代码。所有尝试做的就是从阵列中删除产品。当我调用方法 deleteProduct(prod.getId()) 时,它应该删除我首先添加的产品。

我可以使用for循环,那么如何删除数组中的乘积。请问有什么指点吗?

public void deleteProduct(int productId) throws ProductNotFoundException {

Iterator<Product> it = allProducts.iterator();
Product p= null;
int pid = productId;
int i = 0;

if (!allProducts.isEmpty()) {
while(it.hasNext()){
p= it.next();
i= allProducts.indexOf(p);
if (p.getId().equals(productId)){
i= allProducts.indexOf(p);
allProducts.remove(i);
System.out.println("Successfully removed the product " + pid);
return;
}
}
}
throw new ProductNotFoundException ("No Such Product");
}

最佳答案

您可以使用迭代器通过调用Iterator#remove来删除该项目。 :

while(it.hasNext()){
p = it.next();
if (p.getId().equals(productId)) {
it.remove();
System.out.println("Successfully removed the product " + pid);
return;
}
}
throw new ProductNotFoundException ("No Such Product");
<小时/>

根据注释,使用 for 循环作为迭代器:

for(Iterator<Product> it = allProducts.iterator(); it.haNext(); ) {
p = it.next();
if (p.getId().equals(productId)) {
it.remove();
System.out.println("Successfully removed the product " + pid);
return;
}
}
throw new ProductNotFoundException ("No Such Product");

您可能会问如何在增强的 for 循环中执行此操作?答案是,不能。但由于增强的 for 在后台使用迭代器,因此 while 循环方法将满足您的需求。

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

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