Given a list in Java, the task is to remove all the elements in the sublist whose index is between fromIndex, inclusive, and toIndex, exclusive. The range of the index is defined by the user.
Example:
Input list = [1, 2, 3, 4, 5, 6, 7, 8], fromIndex = 2, endIndex = 4
Output [1, 2, 5, 6, 7, 8]Input list = [‘G’, ‘E’, ‘E’, ‘G’, ‘G’, ‘K’, ‘S’], fromIndex = 3, endIndex = 5
Output [‘G’, ‘E’, ‘E’, ‘K’, ‘S’]
-
Method 1: Using subList() and clear() method
Syntax:
List.subList(int fromIndex, int toIndex).clear()
Example:
// Java code to remove a subList using// subList(a, b).clear() methodÂÂimportjava.util.*;ÂÂpublicclassAbstractListDemo {   Âpublicstaticvoidmain(String args[])   Â{       Â// Creating an empty AbstractList       ÂAbstractList<String>           Âlist =newLinkedList<String>();       Â// Using add() method       Â// to add elements in the list       Âlist.add("GFG");       Âlist.add("for");       Âlist.add("Geeks");       Âlist.add("computer");       Âlist.add("portal");       Â// Output the list       ÂSystem.out.println("Original List: "                          Â+ list);       Â// subList and clear method       Â// to remove elements       Â// specified in the range       Âlist.subList(1,3).clear();       Â// Print the final list       ÂSystem.out.println("Final List: "                          Â+ list);   Â}}Output:Original List: [GFG, for, Geeks, computer, portal] Final List: [GFG, computer, portal]
Note: Classes which can inherit AbstractList:
-
Method 2: Using removeRange() method
Syntax:
List.removeRange(int fromIndex, int toIndex)
Example:
// Java code to remove a subList// using removeRange() methodÂÂimportjava.util.*;ÂÂ// since removeRange() is a protected method// ArrayList has to be extend the classpublicclassGFGextendsArrayList<Integer> {   Âpublicstaticvoidmain(String[] args)   Â{       Â// create an empty array list       ÂGFG arr =newGFG();       Â// use add() method       Â// to add values in the list       Âarr.add(1);       Âarr.add(2);       Âarr.add(3);       Âarr.add(4);       Âarr.add(5);       Âarr.add(6);       Âarr.add(7);       Âarr.add(8);       Â// prints the list before removing       ÂSystem.out.println("Original List: "                          Â+ arr);       Â// removing elements in the list       Â// from index 2 to 4       Âarr.removeRange(2,4);       ÂSystem.out.println("Final List: "                          Â+ arr);   Â}}Output:Original List: [1, 2, 3, 4, 5, 6, 7, 8] Final List: [1, 2, 5, 6, 7, 8]
