I have a list of items, where each item is a simple class containing 2 public strings.
I have an equals method that simply makes use of the equalsIgnoreCase methot of String for both strings.
public class data
{
public String a;
public String b;
public boolean equals(data d)
{
if(a.equalsIgnoreCase(d.a) && b.equalsIgnoreCase(d.b))
{
return true;
}
else
{
return false;
}
}
}
I want to be able to remove an element even if it’s not the same instance of the one in the list but equal to it.
Right now I’m doing this:
public void remove(data dataToRemove)
{
for(data i : _list)
{
if(i.equals(dataToRemove))
{
_list.remove(i);
break;
}
}
}
Is there a better way to do this?
A few comments:
equalsmethod does not override theequalsmethod ofObject(argument should be ofObjecttype, notdatatype).equalsmethod to account for nulls etc.hashcode()too when you overrideequals()– if not you might encounter some weird behaviors when using Sets or Maps for example.If you properly override the
equalsmethod, you can then just use theremovemethod.See below the auto generated
equalsandhashcodegenerated by Netbeans, amended to use theequalsIgnoreCasemethod.