Rk R Bairi
Rk R Bairi

Reputation: 1359

check if a list already contains an object with similar values - java

I need to add an object to a list only when the given list does not already contain a object with similar properties

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);  
}

I tried contains() to have a check on the existing list. If the list already has an object say j with j.type = "TypeA" and j.id = "A", I don't want to add that to list.

Can you please help me achieve this by overriding equals or any solution that can do?

Upvotes: 2

Views: 1460

Answers (1)

hbelmiro
hbelmiro

Reputation: 1027

Implement equals() and hashCode() in your Identifier class.

If you don't want to perform a check before adding the element, you can change your listObject from List to Set. A Set is a collection that contains no duplicate elements.

Follows an example of implementation automatically created by 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;
}

Upvotes: 5

Related Questions