1. Introduction
In Java, the ArrayList class provides a method called subList(int fromIndex, int toIndex) which is used to obtain a portion of this list between the specified fromIndex, inclusive, and toIndex, exclusive. In this blog post, we will learn how to use the subList method to extract a sublist from an ArrayList.
2. Program Steps
1. Create an ArrayList and add some elements to it.
2. Print the original ArrayList.
3. Use the subList() method to extract a sublist from the ArrayList.
4. Print the extracted sublist.
3. Code Program
import java.util.ArrayList;
import java.util.List;
public class ArrayListSubList {
public static void main(String[] args) {
// Step 1: Create an ArrayList and add some elements to it
ArrayList<String> animals = new ArrayList<>();
animals.add("Cat");
animals.add("Dog");
animals.add("Elephant");
animals.add("Fox");
animals.add("Giraffe");
// Step 2: Print the original ArrayList
System.out.println("Original ArrayList: " + animals);
// Step 3: Use subList() method to extract a sublist from the ArrayList
List<String> subList = animals.subList(1, 4);
// Step 4: Print the extracted sublist
System.out.println("SubList extracted from ArrayList: " + subList);
}
}
Output:
Original ArrayList: [Cat, Dog, Elephant, Fox, Giraffe] SubList extracted from ArrayList: [Dog, Elephant, Fox]
4. Step By Step Explanation
Step 1: We initialize an ArrayList named animals and populate it with the elements "Cat", "Dog", "Elephant", "Fox", and "Giraffe".
Step 2: The original ArrayList is printed to the console.
Step 3: We use the subList() method to extract a sublist from the ArrayList. The subList method takes two parameters, the fromIndex and the toIndex. In this example, we extract the sublist from index 1 (inclusive) to index 4 (exclusive).
Step 4: The extracted sublist is printed to the console, showing the elements "Dog", "Elephant", and "Fox".