- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- 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);
- Related Articles
- Java Program to Remove elements from the LinkedList
- Remove a specific element from a LinkedList in Java
- Remove a range of elements from the ArrayList in C#
- Remove a range of elements from the List in C#
- Java Program to Access elements from a LinkedList
- Remove characters in a range from a Java StringBuffer Object
- Create an object array from elements of LinkedList in Java
- Remove all elements from a HashSet in Java
- Iterate through elements of a LinkedList using a ListIterator in Java
- Get first and last elements from Java LinkedList
- Implement a stack from a LinkedList in Java
- Java Program to remove all elements from a set in Java
- How to remove an element from ArrayList or, LinkedList in Java?
- Java Program to Add elements to a LinkedList
- Java program to remove duplicates elements from a List

Advertisements