How to remove specific object from ArrayList in Java?
If you are using Java 8 or above:
test.removeIf(t -> t.i == 1);
Java 8 has a removeIf
method in the collection interface. For the ArrayList, it has an advanced implementation (order of n).
In general an object can be removed in two ways from an ArrayList
(or generally any List
), by index (remove(int)
) and by object (remove(Object)
).
In this particular scenario: Add an equals(Object)
method to your ArrayTest
class. That will allow ArrayList.remove(Object)
to identify the correct object.
ArrayList
removes objects based on the equals(Object obj)
method. So you should implement properly this method. Something like:
public boolean equals(Object obj) {
if (obj == null) return false;
if (obj == this) return true;
if (!(obj instanceof ArrayTest)) return false;
ArrayTest o = (ArrayTest) obj;
return o.i == this.i;
}
Or
public boolean equals(Object obj) {
if (obj instanceof ArrayTest) {
ArrayTest o = (ArrayTest) obj;
return o.i == this.i;
}
return false;
}
For removing the particular object from arrayList there are two ways. Call the function of arrayList.
- Removing on the basis of the object.
arrayList.remove(object);
This will remove your object but in most cases when arrayList contains the items of UserDefined DataTypes, this method does not give you the correct result. It works fine only for Primitive DataTypes. Because user want to remove the item on the basis of object field value and that can not be compared by remove function automatically.
- Removing on the basis of specified index position of arrayList. The best way to remove any item or object from arrayList. First, find the index of the item which you want to remove. Then call this arrayList method, this method removes the item on index basis. And it will give the correct result.
arrayList.remove(index);