Java remove object method

remove(Object obj) method example Java ArrayList

In this tutorial, we will learn about the remove(Object obj) method which removes the specified object from the list. In the last tutorial I have shared how to remove element at the specified index in ArrayList using remove(int index) method.

According to Oracle docs, remove(Object obj) method removes the first occurrence of the specified element from the list, if it is present. Otherwise, if the specified element doesn’t exist in the list, then the list is unchanged.

Syntax:

The syntax of the remove(Object obj) method of Java ArrayList is:

public boolean remove(Object obj)

Parameters:

obj: The element needs to be removed from the list, if it is present.

Returns:

Java ArrayList remove(Object obj) example

1. Remove String object

In the below example, after adding elements to the ArrayList, we are removing a few String elements from it.

import java.util.*; public class RemoveObjectMethodExample < public static void main(String args[]) < // Creating an object of ArrayList of String Type ArrayList arrlist = new ArrayList(); arrlist.add("Apple"); arrlist.add("Google"); arrlist.add("Meta"); arrlist.add("Netflix"); arrlist.add("Amazon"); System.out.println("String ArrayList before remove method: "); for(String s : arrlist) < System.out.println(s); > // remove(obj) method returns true if the obj is present in the ArrayList boolean bool = arrlist.remove("Meta"); System.out.println("Meta is removed: "+bool); // remove(obj) method returns false if the obj is not present in the ArrayList arrlist.remove("IBM"); System.out.println("String ArrayList after applying remove method: "); for(String s2 : arrlist) < System.out.println(s2); > > >

Output:
String ArrayList before remove method:
Apple
Google
Meta
Netflix
Amazon
Meta is removed: true
String ArrayList after applying remove method:
Apple
Google
Netflix
Amazon

2. Remove Integer object

In the below example, after adding elements to the ArrayList, we are removing a few Integer elements from it.

import java.util.*; public class RemoveObjectMethodExample2 < public static void main(String args[]) < // Creating an object of ArrayList of Integer Type ArrayList arrlist = new ArrayList(); arrlist.add(new Integer(1111)); arrlist.add(new Integer(2222)); arrlist.add(new Integer(3333)); arrlist.add(new Integer(4444)); arrlist.add(new Integer(5555)); System.out.println("Integer ArrayList before remove method: "); for(Integer i : arrlist) < System.out.println(i); > // remove(obj) method returns true if the obj is present in the ArrayList boolean bool = arrlist.remove(new Integer(2222)); System.out.println("2222 is removed: " + bool); // remove(obj) method ) returns false if the obj is not present in the ArrayList arrlist.remove(new Integer(6666)); System.out.println("Integer ArrayList after applying remove method: "); for(Integer i2 : arrlist) < System.out.println(i2); > > >

Output:
Integer ArrayList before remove method:
1111
2222
3333
4444
5555
2222 is removed: true
Integer ArrayList after applying remove method:
1111
3333
4444
5555

That’s all for today. Please mention in the comments in case you have any questions related to Java ArrayList remove(Object obj) method example.

Читайте также:  Css transform font weight

About The Author

Subham Mittal has worked in Oracle for 3 years.
Enjoyed this post? Never miss out on future posts by subscribing JavaHungry

Источник

remove() in Java

Java Course - Mastering the Fundamentals

The use of the remove method can be found more often in the Java Collection framework. The remove method removes the specified element from any collection of objects. However, the ways to remove an object might differ in one case or the other.

Syntax

The remove() method in ArrayList equips you with the ability to remove an element in two different ways.

    To begin with, you are supposed to know the object itself to get it removed from the list.

Parameters of remove() in Java

The remove method takes a single parameter.

Return values of remove() in Java

  • The remove method returns true if an object passed as a parameter is removed from the list. Otherwise, it returns false.
  • The remove method returns the removed element if an index is passed.
    • It throws IndexOutOfBoundsException if the specified index is not in range.

    Example

    Return values of remove() in Java

    The given figure also shows the use of boxing an argument so that the remove() method considers the actual object instead of the ASCII value of any char data.

    The return value depends on the parameter of the remove method.

    Since character A is present inside the list, the remove method will remove the character and return true.

    But, what if we pass a character that is not present in the ArrayList? The remove method simply returns false in this case.

    Time Complexity of remove(int index) Method

    The time complexity of remove(int index) Method is O(N) .

    ArrayList implements RandomAccess interface, so accessing any random element will be done in O(1) complexity. However, since the remaining elements also need to be shifted by one place to their left, the overall time complexity becomes O(N) .

    Alternatively, if the index is passed as a parameter, the remove method will remove and return the removed element as well. However, if the index is not in the range of the ArrayList , the remove method throws IndexOutOfBoundsException .

    IndexOutOfBoundsException.

    Time complexity of remove(Object obj) Method

    The time complexity of remove(Object obj) method is O(N) .

    When we pass an object to the remove method, it has to iterate through every element in the list until it finds out the one needed for removal. And obviously, the remaining elements on the right also need to be shifted. So, the overall time complexity is O(N) .

    Exceptions for remove() in in Java

    IndexOutOfBoundsException

    The java.lang.IndexOutOfBoundsException exception is thrown when the index in remove(int index) method is out of range.

    ConcurrentModificationException

    When we use this method while iterating over the elements of the ArrayList, it may result in ConcurrentModificationException because such modifications are not allowed in the ArrayList while we are iterating over its elements simultaneously.

    Solution to ConcurrentModificationException: Iterator interface

    The alternative here is to use the remove method of the Iterator interface.

    Implementation:

    Let us consider a simple example of an ArrayList that stores several characters. We need to focus on what happens when we remove an element from the ArrayList.

    Time Complexity:

    Notice that the removal of C also led to the shifting of all its proceeding elements by one place to their left.

    We’ll be looking at a few more examples to understand the variants of the remove method.

    remove() in Java

    The remove method in Java has varied uses in the Collection interface. Although the operation is to simply remove an object from a collection of objects, it has several variants where the parameters, as well as the return values, differ.

    In our discussion, we’ll be primarily focusing on the use of the remove method in ArrayList. Also, the use of the remove method in Set, Maps and Queues has been demonstrated in the end.

    More Examples

    1. Remove the Specified Element From the ArrayList

    Time Complexity:

    2. Remove the Element from the Specified Position

    Time Complexity:

    3. Remove the First Occurrence of the Element

    If an element appears more than once in the ArrayList, then it will remove it at the first location only.

    Other Uses of Remove() in Java

    The remove() method is implemented in the other interfaces too, including Set, Queue, Maps, etc. Let us take a quick look at some of the examples related to each one of these interfaces where the remove() method is used. Since Set, Queue, Maps are interfaces, we’ll need a class that implements these interfaces to create objects.

    Queue

    Queue is a data structure that follows the First In First Out (FIFO) order. It is similar to a real queue where the person at the front end of the queue will be favored first. The Queue interface is already present in Java which is implemented by other classes. Here, the class LinkedList has been used to implement Queue interface.

    Time Complexity: O(N) where N is the size of the Linked List.

    Explanation:

    • LinkedList class in Queue has an array as its underlying data structure. So, the removal of any element doesn’t require the shifting of other elements.
    • However, we still have to traverse the LinkedList to find the element to be removed.

    Set

    Set is a Collection interface in Java that contains a group of objects without maintaining their insertion order. Also, it doesn’t allow the insertion of duplicate values.

    For the Set interface, we’ll be demonstrating with the help of LinkedHashSet.

    Time Complexity: O(1)

    • LinkedHashSet is the combination of HashSet as well as LinkedList. The remove method in LinkedHashSet works in O(1) time complexity.
    • It is because LinkedHashSet maintains links between the nodes in addition to the hash table.
    • It is not necessary to traverse the whole list for removal, only the list neighbors need to be updated.
    • Accessing a specific element is no more expensive than for the HashSet.

    Map

    Map is an interface that stores a group of key-value pairs as objects, where a key can be used to fetch its mapped value. We’ll be using HashMap to implement the Map interface.

    Time Complexity: O(1)

    HashMap uses Hash Table as its data structure. The remove method in HashMap consumes O(1) time. The put method also has O(1) time complexity. So, the overall time complexity will be O(1).

    Conclusion

    • The remove method is present in the Java Collection framework. We can remove an element from a collection of objects with the help of remove() in java.
    • There are two ways to pass a parameter to the remove method.
    • If we pass an object, then the remove method returns true if the removal is successful, else it returns false. boolean remove (Object obj);
    • If an index is passed as a parameter, the remove method removes the element at the specified index. Object remove(int index); If the index is out of range of the ArrayList, it will throw IndexOutOf BoundsException.
    • If there are multiple occurrences of the same element in the ArrayList, then the remove method will remove its first occurrence only.
    • The overall time complexity of both the variations of remove method in ArrayList will be O(N) , where N is the number of inputs.
    • Using ArrayList.remove() method while iteration may result in ConcurrentModificationException .
    • The remove method also finds its use in the interfaces like Set, Map, Queue, etc.

    Источник

    Java.util.ArrayList.remove(Object) Method

    The java.util.ArrayList.remove(Object) method removes the first occurrence of the specified element from this list, if it is present.If the list does not contain the element, it is unchanged.

    Declaration

    Following is the declaration for java.util.ArrayList.remove() method

    public boolean remove(Object o)

    Parameters

    o − The element to be removed from this list, if present.

    Return Value

    This method returns true if this list contained the specified element, else the list is unchanged.

    Exception

    Example

    The following example shows the usage of java.util.ArrayList.remove(object) method.

    package com.tutorialspoint; import java.util.ArrayList; public class ArrayListDemo < public static void main(String[] args) < // create an empty array list with an initial capacity ArrayListarrlist = new ArrayList(5); // use add() method to add values in the list arrlist.add("G"); arrlist.add("E"); arrlist.add("F"); arrlist.add("M"); arrlist.add("E"); System.out.println("Size of list: " + arrlist.size()); // let us print all the values available in list for (String value : arrlist) < System.out.println("Value = " + value); >// Removes first occurrence of "E" arrlist.remove("E"); System.out.println("Now, Size of list: " + arrlist.size()); // let us print all the values available in list for (String value : arrlist) < System.out.println("Value result notranslate">Size of list: 5 Value = G Value = E Value = F Value = M Value = E Now, Size of list: 4 Value = G Value = F Value = M Value = E

    Источник

    Java ArrayList remove(Object obj) Method example

    The method remove(Object obj) removes the specified object from the list. It belongs to the java.util.ArrayList class.

    public boolean remove(Object obj)

    • It returns false if the specified element doesn’t exist in the list.
    • If there are duplicate elements present in the list it removes the first occurrence of the specified element from the list.

    Example

    In this example we have an ArrayList and we are removing few strings from the list.

    package beginnersbook.com; import java.util.ArrayList; public class RemoveExample < public static void main(String args[]) < //String ArrayList ArrayListal = new ArrayList(); al.add("AA"); al.add("BB"); al.add("CC"); al.add("DD"); al.add("EE"); al.add("FF"); System.out.println("ArrayList before remove:"); for(String var: al) < System.out.println(var); >//Removing element AA from the arraylist al.remove("AA"); //Removing element FF from the arraylist al.remove("FF"); //Removing element CC from the arraylist al.remove("CC"); /*This element is not present in the list so * it should return false */ boolean b=al.remove("GG"); System.out.println("Element GG removed: "+b); System.out.println("ArrayList After remove:"); for(String var2: al) < System.out.println(var2); >> >
    ArrayList before remove: AA BB CC DD EE FF Element GG removed: false ArrayList After remove: BB DD EE

    About the Author

    I have 15 years of experience in the IT industry, working with renowned multinational corporations. Additionally, I have dedicated over a decade to teaching, allowing me to refine my skills in delivering information in a simple and easily understandable manner.

    Источник

Оцените статью