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:
import java.util.*;
public class AbstractListDemo {
public static void main(String args[])
{
AbstractList<String>
list = new LinkedList<String>();
list.add( "GFG" );
list.add( "for" );
list.add( "Geeks" );
list.add( "computer" );
list.add( "portal" );
System.out.println( "Original List: "
+ list);
list.subList( 1 , 3 ).clear();
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:
import java.util.*;
public class GFG extends ArrayList<Integer> {
public static void main(String[] args)
{
GFG arr = new GFG();
arr.add( 1 );
arr.add( 2 );
arr.add( 3 );
arr.add( 4 );
arr.add( 5 );
arr.add( 6 );
arr.add( 7 );
arr.add( 8 );
System.out.println( "Original List: "
+ arr);
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]
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
18 Jan, 2019
Like Article
Save Article