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
I have tried this and it works for me:
ArrayList<cartItem> cartItems= new ArrayList<>();
//filling the cartItems
cartItem ci=new cartItem(itemcode,itemQuantity);//the one I want to remove
Iterator<cartItem> itr =cartItems.iterator();
while (itr.hasNext()){
cartItem ci_itr=itr.next();
if (ci_itr.getClass() == ci.getClass()){
itr.remove();
return;
}
}
This helped me:
card temperaryCardFour = theDeck.get(theDeck.size() - 1);
theDeck.remove(temperaryCardFour);
instead of
theDeck.remove(numberNeededRemoved);
I got a removal conformation on the first snippet of code and an un removal conformation on the second.
Try switching your code with the first snippet I think that is your problem.
Nathan Nelson
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;
}
If you are using Java 8:
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.
If you want to remove multiple objects that are matching to the property try this.
I have used following code to remove element from object array it helped me.
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)).
some time for you arrayList.remove(index)
or arrayList.remove(obj.get(index))
using these lines may not work try to use following code.
for (Iterator<DetailInbox> iter = detailInboxArray.iterator(); iter.hasNext(); ) {
DetailInbox element = iter.next();
if (element.isSelected()) {
iter.remove();
}
}