Remove equal element from java list
I have a list of items where each item is a simple class containing two public strings. I have an equals method that just uses the equalsIgnoreCase sign for 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 remove an item, even if it is not the same instance from the list in the list, but equal to it.
I am doing this now:
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?
source to share
A few comments:
- Your
equals
method does not override the methodequals
Object
(the argument must be of typeObject
, notdata
). - You should improve your method
equals
to account for zeros, etc. - And finally, you should override
hashcode()
when overriding tooequals()
- unless you encounter some strange behavior when using sets or maps, for example.
If you override the method correctly equals
, you can simply use the method remove
. Below are the auto-generated equals
and hashcode
generated Netbeans, amended to use the method equalsIgnoreCase
.
public static void main(String[] args) {
List<Data> list = new ArrayList<Data>();
list.add(new Data("a", "b"));
list.add(new Data("a", "c"));
System.out.println(list.size()); //2
list.remove(new Data("A", "b"));
System.out.println(list.size()); //1
}
public static class Data {
public String a;
public String b;
public Data(String a, String b) {
this.a = a;
this.b = b;
}
@Override
public boolean equals(Object obj) {
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
final Data other = (Data) obj;
boolean sameA = (this.a == other.a) || (this.a != null && this.a.equalsIgnoreCase(other.a));
if (!sameA) return false;
boolean sameB = (this.b == other.b) || (this.b != null && this.b.equalsIgnoreCase(other.b));
if (!sameB) return false;
return true;
}
@Override
public int hashCode() {
int hash = 3;
hash = 89 * hash + (this.a == null ? 0 :this.a.toUpperCase().hashCode());
hash = 89 * hash + (this.b == null ? 0 : this.b.toUpperCase().hashCode());
return hash;
}
}
source to share
The easiest way is to simply call the Remove method of the list without any loops and pass a parameter to your object. It uses the equals method you defined on the object to find and remove it if it exists in the list.
_list.remove(data);
You also don't need to specify the hashcode method, but you should get in the habit of always creating it when you override the equals method, if you are using it on a collection like Set or Map.
source to share