Nội dung chính
Xem Remove(Object in list Java) 2024
ArrayList is similar to the array whose size can be modified. The ArrayList class is available in the Java.util package and extends the List interface. Adding and removing an element from the ArrayList is very easy by using its built-in methods add() and remove(). However, there is more than one way of removing an element from the ArrayList that are as follows:
- Using ArrayList.remove() Method
- Using Iterator.remove() Method
- Using ArrayList.removeIf() Method
All these three ways are best in their own, and can be used in some different scenario. Let’s understand all these three ways, one by one.
ArrayList.remove() Method
Using the remove() method of the ArrayList class is the fastest way of deleting or removing the element from the ArrayList. It also provides the two overloaded methods, i.e., remove(int index) and remove(Object obj). The remove(int index) method accepts the index of the object to be removed, and the remove(Object obj) method accepts the object to be removed.
Let’s take an example to understand how the remove() method is used.
RemoveMethod.java
Output:
Let’s take another example to understand how the remove() method is used to remove the specified element from the ArrayList.
RemoveElementMethod.java
Output:
Iterator.remove() Method
The Iterator.remove() method is another way of removing an element from an ArrayList. It is not so helpful in case when iterating over elements. When we use the remove() method while iterating the elements, it throws the ConcurrentModificationException. The Iterator class removes elements properly while iterating the ArrayList.
Let’s take an example to understand how the Iterator.remove() method is used.
IteratorRemoveMethod.java
Output:
ArrayList.removeIf() Method
If we want to remove an element from the ArrayList which satisfy the predicate filter, the removeIf() method is best suited for this case. We pass the predicate filter to that method as an argument.
Let’s take an example to understand how the removeIf() method is used.
RemoveIfMethod.java
Output:
All of the above-discussed methods are used for different scenarios. Using ArrayList.remove() method is the fastest way for removing an element from the ArrayList.
Bạn đang tìm hiểu bài viết: Remove(Object in list Java) 2024
HỆ THỐNG CỬA HÀNG TRÙM SỈ QUẢNG CHÂU
Điện thoại: 092.484.9483
Zalo: 092.484.9483
Facebook: https://facebook.com/giatlathuhuongcom/
Website: Trumsiquangchau.com
Địa chỉ: Ngõ 346 Nam Dư, Trần Phú, Hoàng Mai, Hà Nội.