Tag Archives: ArrayList

List.contains(Object e) – Howto

If you have a List of Custom object, and you would like to perform operations such as “contains” or “remove” on this List, you need to do the following.

Implement equals(Object o) method in your custom class, note, the method takes Object as a parameter not the custom object as the type, this is because the the code in the contains method in the List (ArrayList) class, does the followng

public int indexOf(Object elem) {
if (elem == null) {
for (int i = 0; i < size; i++)
if (elementData[i]==null)
return i;
} else {
for (int i = 0; i < size; i++)
if (elem.equals(elementData[i]))
return i;
}
return -1;
}

example method :

public boolean equals(Object bean)
{
boolean result = false;
CustomObject gbean = (CustomObject) bean;

if(Id.equalsIgnoreCase(gbean.getId()))
{
result = true;
}
return result;
}

 

Advertisements

Leave a comment

Filed under Java