A linked list is a collection of linear data elements. Each element (node) contains data and reference parts. The data part has the value, and the reference part has the address link to the next element. The elements are not indexed so random access is not possible. Instead, we traverse from the beginning of the list to access the elements.
In Java, the
LinkedList
is aimplementation of the List and Deque interfaces. The doubly-linked list This is a type of linked list. Each node contains three fields. It has two link fields (one for the previous element and another for the next element) and one data field. LinkedList
class is present in thejava.util
package.
clear
method of the LinkedList
class?The clear
method can be used to delete all the elements of the LinkedList
. After calling this method, the list becomes empty.
public void clear();
This method doesn’t take any parameters and doesn’t return any value.
The code below demonstrates the use of the clear
method:
import java.util.LinkedList;class LinkedListClear {public static void main( String args[] ) {LinkedList<String> list = new LinkedList<>();list.add("1");list.add("2");list.add("3");System.out.println("The list is " + list);list.clear();System.out.println("After calling the clear method the list is " + list);}}
In the code above:
LinkedList
class.import java.util.LinkedList;
LinkedList
object named list
.LinkedList<String> list = new LinkedList<>();
add
method of the list
object to add three elements("1","2","3"
) to the list.list.add("1");
list.add("2");
list.add("3");
clear
method of the list
object to remove all the list elements.list.clear();
After calling the clear
method, the list becomes empty.