How to delete many elements from a linkedList in Java
Problem Description
How to delete many elements from a linkedList?
Solution
Following example demonstrates how to delete many elements of linkedList using Clear() method.
import java.util.*;
public class Main {
public static void main(String[] args) {
LinkedList<String> lList = new LinkedList<String>();
lList.add("1");
lList.add("8");
lList.add("6");
lList.add("4");
lList.add("5");
System.out.println(lList);
lList.subList(2, 4).clear();
System.out.println(lList);
}
}
Result
The above code sample will produce the following result.
[1, 8, 6, 4, 5] [1, 8, 5]
The following is an another sample example to delete many elements of linkedList using Clear() method.
import java.util.LinkedList;
public class Demo {
public static void main(String[] args) {
LinkedList lList = new LinkedList();
lList.add("1");
lList.add("2");
lList.add("3");
lList.add("4");
lList.add("5");
System.out.println("LinkedList is : " +lList);
lList.subList(2, 4).clear();
System.out.println("LinkedList is : " +lList);
}
}
The above code sample will produce the following result.
LinkedList is : [1, 2, 3, 4, 5] LinkedList is : [1, 2, 5]
java_data_structure.htm
Advertisements