查找List是否包含具有属性的对象

时间:2017-11-22 16:24:55

标签: java

我有3个列表: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的内容,但仅限于包含完整对象等的内容。

无论如何都要以一种我想念的简单方式完成这项工作?

1 个答案:

答案 0 :(得分:0)

为什么在你已经检查'for'循环中是否有一个带有该ID的对象时,你想要做if (customers.contains(customerId) && items.contains(itemId))这样的事情?看起来它只会删除'if'语句。

相关问题