使用indexOf但使用List中包含的类的成员

时间:2011-12-07 21:09:12

标签: java collections

我在想什么。如果我有这样的课程:

public class OrderItem {
    private Item item;
    private int quantity;
    private BigDecimal total;
}

我在课堂上ChartList<OrderItem> ordersOrderItem标识了item,因此我在想是否有orders我可以考虑(indexOf)的方法来检查是否存在OrderItem然后检索它(或其索引)

我说的是与使用for循环不同的东西并检查其项目。也许是一个界面?

编辑:对不起我误导了这个问题,我忘记了一个重要的部分。我需要检索对象。

2 个答案:

答案 0 :(得分:3)

如果您覆盖List

contains()方法,则可以使用OrderItem contains()方法

来自equals的文档:

  

如果此列表包含指定的元素,则返回true。更正式地说,当且仅当此列表包含至少一个元素e时才返回true(o == null?e == null:o.equals(e))。

在覆盖Item之内,比较您的equals()并根据需要返回true / false。如果您覆盖hashcode(),则还应覆盖equals()

编辑:在回复评论时,以上内容也适用于equals() - 一旦实施contains(),索引也将与OrderItem的工作方式相同。只需向其提供包含相同Item的{​​{1}}实例,然后您将在匹配的OrderItem(如果有)列表中找回该索引,然后可以使用该索引访问它。

答案 1 :(得分:2)

.equals()中覆盖.hashcode()OrderItem,因此相等性由item确定。

然后,您可以调用indexOf(dummyOrderItem),其中dummyOrderItem是使用正确的item创建的虚拟对象。然后,您可以调用get(index)来检索真实对象。

如果您使用Eclipse,则可以使用source->generate hashCode() and equals()自动生成这些方法:

@Override
public int hashCode()
{
    final int prime = 31;
    int result = 1;
    result = prime * result + ((item == null) ? 0 : item.hashCode());
    return result;
}
@Override
public boolean equals(Object obj)
{
    if (this == obj)
        return true;
    if (obj == null)
        return false;
    if (getClass() != obj.getClass())
        return false;
    OrderItem other = (OrderItem) obj;
    if (item == null)
    {
        if (other.item != null)
            return false;
    }
    else if (!item.equals(other.item))
        return false;
    return true;
}