![]() |
In Java, ArrayList.clear() and ArrayList.removeAll() are the two methods that are used to remove elements from an ArrayList, but they are used for different purposes. In this article will explain the difference between the two methods. 1. ArrayList.clear() MethodThe clear() method of ArrayList in Java is used to remove all the elements from a list. Syntax:public void clear() Parameters: The clear method does not need any parameters. Return Type: It does not return any value as it removes all the elements in the list and makes it empty. Example of ArrayList.clear() MethodThis example shows the implementation of the ArrayList.clear() method.
Output The list initially: [Geeks, for, geeks] The list after using clear() method: [] Explanation of the above Program: In this example, we create a new ArrayList called “list” and add some elements to it using the add() method. Then, we print the elements of the ArrayList. Next, we call the clear() method to remove all elements from the ArrayList. Finally, we print the elements of the ArrayList again to demonstrate that it is now empty. 2. ArrayList.removeAll() methodThis method is used to remove all the elements present in the collection from the specified list. Syntax:boolean removeAll(Collection c) Parameters: This method has only argument, collection of which elements are to be removed from the given list. Return Type: This method returns True if elements are removed and list changes. Example of ArrayList.removeAll() MethodThis example shows the implementation of the ArrayList.removeAll() method.
Output List after removeAll: [2, 3] Is the elements are removed? true Explanation of the above Program:In this example, we create a new ArrayList called “result” add some elements to it using the add() method. Then we need to create a collection and provide a parameter into the collection which containing elements that are to be removed from the ArrayList. Next, we call the removeAll() method to remove elements from the ArrayList. Finally, we print the elements of the ArrayList again to demonstrate that the elements are removed. And You can print the boolean result also. Difference between ArrayList.clear() and ArrayList.removeAll()
|
Reffered: https://www.geeksforgeeks.org
Java |
Related |
---|
![]() |
![]() |
![]() |
![]() |
![]() |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 16 |