
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Clear LinkedList in Java
An LinkedList can be cleared in Java using the method java.util.LinkedList.clear(). This method removes all the elements in the LinkedList. There are no parameters required by the LinkedList.clear() method and it returns no value.
A program that demonstrates this is given as follows.
Example
import java.util.LinkedList; public class Demo { public static void main(String[] args) { LinkedList<String> l = new LinkedList<String>(); l.add("Orange"); l.add("Apple"); l.add("Peach"); l.add("Guava"); System.out.println("LinkedList before using the LinkedList.clear() method: " + l); l.clear(); System.out.println("LinkedList after using the LinkedList.clear() method: " + l); } }
The output of the above program is as follows
LinkedList before using the LinkedList.clear() method: [Orange, Apple, Peach, Guava] LinkedList after using the LinkedList.clear() method: []
Now let us understand the above program.
The LinkedList l is created. Then LinkedList.add() is used to add the elements to this LinkedList. The LinkedList is displayed before and after using theLinkedList.clear() method which clears the LinkedList. A code snippet which demonstrates this is as follows
LinkedList<String> l = new LinkedList<String>(); l.add("Orange"); l.add("Apple"); l.add("Peach"); l.add("Guava"); System.out.println("LinkedList before using the LinkedList.clear() method: " + l); l.clear(); System.out.println("LinkedList after using the LinkedList.clear() method: " + l);
Advertisements