33

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>

Ripon Al Wasim
  • 36,924
  • 42
  • 155
  • 176
sAaNu
  • 1,428
  • 7
  • 21
  • 46

17 Answers17

50

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;
}
Valchev
  • 1,490
  • 14
  • 17
37

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

Tmh
  • 1,321
  • 14
  • 27
20

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.

Bombe
  • 81,643
  • 20
  • 123
  • 127
6

For removing the particular object from arrayList there are two ways. Call the function of arrayList.

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

  1. 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);  
Mika Sundland
  • 18,120
  • 16
  • 38
  • 50
Aman Goyal
  • 409
  • 5
  • 8
6

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 + "]";
    }

}

Working demo Screen

Vipul Gulhane
  • 761
  • 11
  • 16
3

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.
Kashif Khan
  • 2,615
  • 14
  • 14
  • if there position is irregular then how can i get the index of obj. – sAaNu Dec 15 '11 at 13:32
  • pardon me if i could not understand your point. but you dont need to provide index, you need to pass the object to indexOf method and it will return the object index and remove method will remove this index from the ArrayList. If you have duplicate objects with same value then you need to implement equals method in your class. – Kashif Khan Dec 15 '11 at 13:37
  • but in this case indexOf(obj) retain the index value of last object that is ArrayTest(3).....so it will remove last object – sAaNu Dec 15 '11 at 13:41
  • 1
    use this code 'public void deleteObject(ArrayTest obj) { for(int i=0; i – Kashif Khan Dec 15 '11 at 13:51
1

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();
   }
}
Sagar
  • 5,273
  • 4
  • 37
  • 50
1

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;
    }
}
Ivan Kaloyanov
  • 1,748
  • 6
  • 18
  • 24
1

If you want to remove or filter specific object from ArrayList, there are many ways that you can use it as given below:

Suppose list is the reference variable of arrayList.

List<Student> list = ...;// Stored the objects here  

If you know the specific Student object that you want to delete then you can use it simply:

list.remove(student) //if you know the student object

If you know the specific id or name of that student, in that case, use java 8 Collection.removeIf():

list.removeIf(fandom -> id == fandom.getId());

Another way that you can use that is Collectors.partitioningBy:

Map<Boolean, List<Student>> studentsElements = list
.stream()
.collect(Collectors.partitioningBy((Student st) ->       
                  !name.equals(st.getName())));

// All Students who do have not that specific name
List<Student> matching = studentsElements.get(true));
// All Student who has only that specific name
List<Student> nonMatching = studentsElements.get(false));

Or you can simply filter that specific Object

List<Student> studentsElements = list
.stream()
.filter(e -> !name.equals(st.getName()))
.collect(Collectors.toList());
vikash
  • 381
  • 2
  • 11
1

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.

Tatarasanu Victor
  • 656
  • 1
  • 7
  • 19
0

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

0

simple use remove() function. and pass object as param u want to remove. ur arraylist.remove(obj)

Ali
  • 331
  • 3
  • 5
0

or you can use java 8 lambda

test.removeIf(i -> i==2);

it will simply remove all object that meet the condition

Ali
  • 331
  • 3
  • 5
0

Below one is used when removed ArrayTest(1) from test ArrayList

test.removeIf(
     (intValue) -> {
         boolean remove = false;
         remove = (intValue == 1);
         if (remove) {
            //Success
         }
         return remove;
      });
Pratik Dodiya
  • 2,337
  • 1
  • 19
  • 12
0

Example within a simple String List, if anyone wants :

 public ArrayList<String> listAfterRemoved(ArrayList<String> arrayList, String toRemove) {

        for (int i = 0; i < arrayList.size(); i++) {
            if (arrayList.get(i).equals(toRemove)) {
                arrayList.remove(toRemove);
            }
        }
        return arrayList;
    }

And the call is :

ArrayList<String> arrayList = new ArrayList<>();
        arrayList.add("1");
        arrayList.add("2");
        arrayList.add("3");
        arrayList.add("4");

        System.out.println("Array List before: " + arrayList.toString());
        arrayList = listAfterRemoved(arrayList, "2");
        System.out.println("Array List after : " + arrayList.toString());

enter image description here

Noor Hossain
  • 1,620
  • 1
  • 18
  • 25
0
    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.

Pritom
  • 1,294
  • 8
  • 19
  • 37
0

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.

Alan Delimon
  • 817
  • 7
  • 14