[英]Find if List contains object with property
我有3个列表:“ Sales, Customers, Items
持有自己名字的对象的Sales, Customers, Items
。
我有一个方法:
public boolean sellItem(int itemId, int customerId) {
if (customers.contains(customerId) && items.contains(itemId)){
for (Item i : items) {
if(i.getItemId() == itemId && i.getStockNum()>0) {
sales.add(new Sale(LocalDateTime.now(), itemId, customerId, i.getCost()));
i.sell();
}
for (Customer c : customers) {
if (c.getCustomerId() == customerId) {
c.charge(i.getCost());
}
}
}
return true;
}
return false;
}
但是我知道,我找不到列表是否包含类似其ID的内容,只有在它们包含完整对象等的情况下才能找到。
无论如何,有什么方法可以使我所缺少的简单方法起作用?
当您已经在“ for”循环中检查是否存在具有该ID的对象时,为什么要执行if (customers.contains(customerId) && items.contains(itemId))
之类的操作? 看起来只删除该“ if”语句就可以了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.