Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove specific object from ArrayList in Java?

Tags:

java

arraylist

How can I remove specific object from ArrayList? Suppose I have a class as below:

import java.util.ArrayList;    
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);
    }
    public ArrayTest(int i){
        this.i=i;
    }
}

How can I remove object with new ArrayTest(1) from my ArrayList<ArrayList>

like image 801
sAaNu Avatar asked Dec 15 '11 13:12

sAaNu


People also ask

How do you remove multiple elements from an ArrayList in Java?

The List provides removeAll() method to remove all elements of a list that are part of the collection provided.


3 Answers

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; } 
like image 62
Valchev Avatar answered Sep 21 '22 17:09

Valchev


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).

like image 42
Tmh Avatar answered Sep 23 '22 17:09

Tmh


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.

like image 39
Bombe Avatar answered Sep 23 '22 17:09

Bombe