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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s