In this method you can delete elements from the list.
clear( ) method of List Interface in java.
In the following example, we will show you the method of removing elements from a list using clear( ) method of List Interface in java.
Syntax
void clear( )
This method does not return any value.
In this method you can delete elements from the list. It deletes all of the elements from a specified list. When this method is called, the list becomes empty.
Parameter description :
This method does not take any argument and also doesn't return any value.
Example of clear( ) method
In this example we will show you how does a clear ( )method work in List interface. This example will help you to understand how elements can be removed from the list. Through this example we will show you adding elements to the list, count the number of elements, and remove the elements from the list
Example:-
package Devmanuals.com; import java.util.List; import java.util.ArrayList; import java.util.LinkedList; public class ListClear { public static void main (String args []){ List al=new ArrayList(); al.add(1); al.add(2); al.add(3); al.add(4); al.add(5); System.out.println("Elements of list1 are : "+al); System.out.println("Size of list1 before removing element is : "+al.size()); //implemntation of clear() al.clear(); System.out.println("Size of list1 after removing elements : "+al.size()); List ll=new LinkedList(); ll.add("Ram"); ll.add("is"); ll.add("a"); ll.add("Boy"); System.out.println("Elements of list2 are : "+ll); System.out.println("Size of list2 before removing element is : "+ll.size()); //implemntation of clear() ll.clear(); System.out.println("Size of list2 after removing elements : "+ll.size()); } }
Output:-
Elements of list1 are : [1, 2, 3, 4, 5] Size of list1 before removing element is : 5 Size of list1 after removing elements : 0 Elements of list2 are : [Ram, is, a, Boy] Size of list2 before removing element is : 4 Size of list2 after removing elements : 0 |
[ 0 ] Comments