
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
Remove a Range of Elements from a LinkedList in Java
A range of elements can be removed from a LinkedList by using the method java.util.LinkedList.clear() along with the method java.util.LinkedList.subList(). 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("Clark"); l.add("Bruce"); l.add("Diana"); l.add("Wally"); l.add("Oliver"); System.out.println("The LinkedList is: " + l); l.subList(1,3).clear(); System.out.println("The LinkedList is: " + l); } }
Output
The LinkedList is: [Clark, Bruce, Diana, Wally, Oliver] The LinkedList is: [Clark, Wally, Oliver]
Now let us understand the above program.
The LinkedList l is created. Then LinkedList.add() is used to add the elements to the LinkedList. Then the LinkedList is displayed. A code snippet which demonstrates this is as follows −
LinkedList<String> l = new LinkedList<String>(); l.add("Clark"); l.add("Bruce"); l.add("Diana"); l.add("Wally"); l.add("Oliver"); System.out.println("The LinkedList is: " + l);
A range of elements from index 1(inclusive) to index 3(exclusive) are removed from the LinkedList using the LinkedList.clear() and the LinkedList.subList() methods. Then the modified LinkedList is displayed. A code snippet which demonstrates this is as follows −
System.out.println("The LinkedList is: " + l); l.subList(1,3).clear(); System.out.println("The LinkedList is: " + l);
Advertisements