How can I remove specific object from ArrayList? Suppose I have a class as below:
import java.util.ArrayList;
public class ArrayTest {
int i;
pu
For removing the particular object from arrayList there are two ways. Call the function of arrayList.
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.
arrayList.remove(index);
Here is full example. we have to use Iterator's remove() method
import java.util.ArrayList;
import java.util.Iterator;
public class ArrayTest {
int i;
public static void main(String args[]) {
ArrayList<ArrayTest> test = new ArrayList<ArrayTest>();
ArrayTest obj;
obj = new ArrayTest(1);
test.add(obj);
obj = new ArrayTest(2);
test.add(obj);
obj = new ArrayTest(3);
test.add(obj);
System.out.println("Before removing size is " + test.size() + " And Element are : " + test);
Iterator<ArrayTest> itr = test.iterator();
while (itr.hasNext()) {
ArrayTest number = itr.next();
if (number.i == 1) {
itr.remove();
}
}
System.out.println("After removing size is " + test.size() + " And Element are :" + test);
}
public ArrayTest(int i) {
this.i = i;
}
@Override
public String toString() {
return "ArrayTest [i=" + i + "]";
}
}
ArrayTest obj=new ArrayTest(1);
test.add(obj);
ArrayTest obj1=new ArrayTest(2);
test.add(obj1);
ArrayTest obj2=new ArrayTest(3);
test.add(obj2);
test.remove(object of ArrayTest);
you can specify how you control each object.
You can use Collections.binarySearch to find the element, then call remove on the returned index.
See the documentation for Collections.binarySearch here: http://docs.oracle.com/javase/1.4.2/docs/api/java/util/Collections.html#binarySearch%28java.util.List,%20java.lang.Object%29
This would require the ArrayTest object to have .equals implemented though. You would also need to call Collections.sort to sort the list. Finally, ArrayTest would have to implement the Comparable interface, so that binarySearch would run correctly.
This is the "proper" way to do it in Java. If you are just looking to solve the problem in a quick and dirty fashion, then you can just iterate over the elements and remove the one with the attribute you are looking for.
AValchev is right. A quicker solution would be to parse all elements and compare by an unique property.
String property = "property to delete";
for(int j = 0; j < i.size(); j++)
{
Student obj = i.get(j);
if(obj.getProperty().equals(property)){
//found, delete.
i.remove(j);
break;
}
}
THis is a quick solution. You'd better implement object comparison for larger projects.
use this code
test.remove(test.indexOf(obj));
test is your ArrayList and obj is the Object, first you find the index of obj in ArrayList and then you remove it from the ArrayList.