how to display and remove the elements within a range using ArrayList
Previous Home Next


In this example we will see how can we display and remove a set of elements in an ArrayList.

In this example we have created a class CollectionExample. For using ArrayList we have
to import the java.util package.
 For creating a subset within an ArrayList we use the subList() method on the ArrayList. To remove the sublist from the ArrayList we use the clear() method on the ArrayList object.

In the following example we have created an ArrayList and then we have added few elements in it. After that we have created a sublist of the elements from 0 to3 index, here 3rd index element is excluded. Then we applied clear() method on that sublist which clear all the elements of the sublist and hence the items are removed from the ArrayList within that range.

The following statement in the example removes the elements within a range:
al.subList(0, 3).clear();

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Collection;

public class CollectionExample {

* @param args
public static void main(String[] args)
// TODO Auto-generated method stub

ArrayList<String> al=new ArrayList<String>(); // creating an ArrayList named al
al.add("r4r"); // adding string objects to the arraylist
al.add("s/w engineer");
System.out.println("The size of the arraylist is: "+al.size()); // determining the length of the arraylist

System.out.println("The contents of the list are :"+al); // showing the contents of the arraylist

System.out.println("The items within the sublist are:"+al.subList(0,3)); // displaying the items between the selected range
al.subList(0, 3).clear(); // clearing all the items in the range
System.out.println("Now the size of the list is : "+al.size()); // displaying the size of the list after removing the items
System.out.println("The contents of the list now are : "+al); // displaying the content of the list after the removing the items


The output of the above program will be as following,

The contents of the list are :[r4r, development, tutorials, shashi, s/w engineer]
The items within the sublist are:[r4r, development, tutorials]
Now the size of the list is : 2
The contents of the list now are : [shashi, s/w engineer]

Previous Home Next