检查列表是否已包含具有相似值的对象 - java

时间:2016-03-24 19:24:48

标签: java arraylist collections

只有当给定列表中还没有包含具有相似属性的对象时,才需要将对象添加到列表中

List<Identifier> listObject; //list
Identifier i = new Identifier(); //New object to be added
i.type = "TypeA";
i.id = "A";
if(!listObject.contains(i)) {   // check
    listObject.add(i);  
}

我尝试contains()检查现有列表。如果列表中有一个对象说j j.type = "TypeA"j.id = "A",我不想将其添加到列表中。

你可以通过覆盖平等或任何可以解决的解决方案来帮助我实现这一目标吗?

1 个答案:

答案 0 :(得分:5)

equals()课程中实施hashCode()Identifier

如果您不想在添加元素之前执行检查,则可以将listObjectList更改为SetSet是一个不包含重复元素的集合。

遵循Eclipse IDE自动创建的实现示例:

@Override
public int hashCode() {
    final int prime = 31;
    int result = 1;
    result = prime * result + ((id == null) ? 0 : id.hashCode());
    result = prime * result + ((type == null) ? 0 : type.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;
    Identifier other = (Identifier) obj;
    if (id == null) {
        if (other.id != null)
            return false;
    } else if (!id.equals(other.id))
        return false;
    if (type == null) {
        if (other.type != null)
            return false;
    } else if (!type.equals(other.type))
        return false;
    return true;
}
相关问题