Tuesday, July 6, 2021

How to remove objects from ArrayList in Java? Example

In this Java ArrayList tutorial, you will learn how to remove elements from ArrayList in Java e.g. you can remove String from ArrayList of String or Integer from ArrayList of Integers. There are actually two methods to remove an existing element from ArrayList, first by using the remove(int index) method, which removes elements with a given index, remember the index starts with zero in ArrayList. So a call to remove(2) in an ArrayList of {"one", "two", "three"} will remove 3rd element which is "three". The second method to remove an element is remove(Object obj), which removes a given object from ArrayList

For example, a call to remove("two") will remove the second element from ArrayList. Though you should remember to use the Iterator or ListIterator remove() method to delete elements while iterating, using ArrayList's remove methods, in that case, will throw ConcurrentModificationException in Java.

Things get a little complicated when you are working with ArrayList of integral numbers like ArrayList of integers. If your list contains numbers which are same as indexes like then a call to remove(int index) can be confused with a call to remove(Object obj).

For example, if you have an ArrayList containing {1, 2, 3} then a call to remove(2) is ambiguous because it could be interpreted as a call to remove 2, which is a second element, or a call to remove the element at index 2, which is actually 3.

If you want to learn more about Collection classes, I suggest you to take a look at one of these free Java Programming courses which  I refer to refresh my knowledge on the topic.




Java ArrayList Remove Example

Here is the Java program to remove a given object from ArrayList in Java. In this example, I have used the second remove method, which deletes the given object from ArrayList. Anyway, since we have an ArrayList of String, you can use any of those method, its safe. You can also check the size() of ArrayList before and after removing elements.

Remember, size() method gives total number of elements in ArrayList, so it should reduce by one. This is different than the size of array which is backing ArrayList, which will remain same. In our example, you can see that number of elements is gradually reduced after removal.

By using index you can easily remove the first or last element from ArrayList in Java. Since index starts at zero in ArrayList, you can remove the first element by passing zero to remove method like remove(0), and to remove the last element from ArrayList, you can pass size - 1 to remove(int index) method like remove(ArrayList.size() - 1) will remove the last element from ArrayList. Remember, unlike an array, there is no length method in ArrayList, so you need to use the size() method which returns a total number of elements in the ArrayList.

Time complexity of remove(int index) method is O(n) because it's not just delete the element at specified index but also shifts any subsequent elements to the left i.e. subtracts one from their indices. For example, if ArrayList has 10 elements and you removed the 4th element i.e. index 3 then all elements starting from 5th to 10th will shift lower e.g. 5th will come to 4th, 6th will come to 5th, and so on.

There is one more method removeAll(Collection c) which you can use to remove all elements specified in the given collection. This method return true if ArrayList changed by calling this method i.e. one more elements are removed. You can use this method to remove elements in bulk from ArrayList. 

This method will throw ClassCastException if the class of the element of this list is not compatible with the class of the element in the given collection. It will also throw NullPointerException if this list contains a null element and specified collection doesn't permit null elements or the specified collection itself is null.

Though, you shouldn't use these methods when you are removing elements while iterating over ArrayList. In that case, you must use Iterator's remove() method to avoid ConcurrentModificationException. 

You can further join these Java collections and Stream API courses to learn more about how to remove objects from ArrayList in Java. One of the most comprehensive yet easy-to-read books on Java programming.




Java Program to remove String from ArrayList

import java.util.ArrayList;

/**
 * ArrayList remove and removeAll Examples
 *
 * @author WINDOWS
 */

public class ArrayListRemoveDemo{

    public static void main(String args[]) {

        ArrayList<String> cities = new ArrayList<>();
        cities.add("London");
        cities.add("Tokyo");
        cities.add("HongKong");
        cities.add("NewYork");
        cities.add("Berlin");
       
       
        System.out.println("Before removing any element from ArrayList : " 
                 + cities);
        cities.remove("London");
       
        System.out.println("After removing one element from ArrayList : " 
                 + cities);
        cities.remove("Tokyo");
       
        System.out.println("After removing two objects from ArrayList : " 
                + cities);
     

    }

}

Output
Before removing any element from ArrayList : 
[London, Tokyo, HongKong, NewYork, Berlin]
After removing one element from ArrayList : 
[Tokyo, HongKong, NewYork, Berlin]
After removing two objects from ArrayList : 
[HongKong, NewYork, Berlin]

Here is another Java example to remove an object at a given index from ArrayList in Java.

How to remove elements form ArrayList in Java



That's all about how to take out an object from ArrayList in Java. Remember there are two methods to remove elements, first remove(int index) and second remove(Object obj), if you are working with ArrayList of Integer, Short, Byte, or Long then autoboxing may cause a problem for you, because a call to remove(1) may be interpreted as calls to remove(index) to remove a second element or a call to remove(Object) to remove the element with value 1. 

This is why you should take care while overloading method with same number of argument, you can avoid this kind of ambiguity by following some overloading best practices.

5 comments:

  1. See here also to learn more about how to remove elements from an ArrayList.

    ReplyDelete
  2. please clarify the ambiguity in case of remove method for interger arraylist

    ReplyDelete
    Replies
    1. The ambiguity occurs when you try to remove an integer from an ArrayList of Integer due to autoboxing. For example, if you have a list containing (1, 2, 3,4 5,) then a call to remove(1) is ambiguous because it can resolve to either remove(new Integer(1)) due to auto-boxing or remove(1) i.e. to remove object at second index.

      Delete
    2. I tried this, when i did list.remove(1) It takes only index not as Object.
      what if i want to remove the Integer object from ArrayList

      Delete
  3. Explain internal algorithm of remove method how it ll remove..

    ReplyDelete

Feel free to comment, ask questions if you have any doubt.