Java ArrayList subList() Method
The subList() method is used to extract and return a portion of the dynamic array.
The syntax for the subList() method is:
arraylist.subList(int fromIndex, int toIndex)
Note: arraylist is an object of the ArrayList class.
Parameter Description:
- fromIndex - The starting position of the elements to be extracted, including the element at this index.
- toIndex - The ending position of the elements to be extracted, excluding the element at this index.
Return Value
Returns the specified portion of the dynamic array.
If fromIndex is less than 0 or greater than the array's length, it throws an IndexOutOfBoundsException.
If fromIndex is greater than toIndex, it throws an IllegalArgumentException.
Note: The dynamic array includes elements starting from the fromIndex position up to the element at index toIndex-1, and the element at index toIndex is not included.
Example
Extracting a sublist from the dynamic array:
import java.util.ArrayList;
class Main {
public static void main(String[] args){
// Create a dynamic array
ArrayList<String> sites = new ArrayList<>();
sites.add("Google");
sites.add("tutorialpro");
sites.add("Taobao");
sites.add("Wiki");
System.out.println("Website List: " + sites);
// Elements from position 1 to 3
System.out.println("SubList: " + sites.subList(1, 3));
}
}
Executing the above program outputs:
Website List: [Google, tutorialpro, Taobao, Wiki]
SubList: [tutorialpro, Taobao]
In the above example, we used the subList() method to get elements from index 1 to 3 (excluding 3).
Splitting a dynamic array into two dynamic arrays:
import java.util.ArrayList;
class Main {
public static void main(String[] args) {
// Create an array
ArrayList<Integer> ages = new ArrayList<>();
// Add elements to the array
ages.add(10);
ages.add(12);
ages.add(15);
ages.add(19);
ages.add(23);
ages.add(34);
System.out.println("Age List: " + ages);
// Under 18
System.out.println("Under 18: " + ages.subList(0, 3));
// Over 18
System.out.println("Over 18: " + ages.subList(3, ages.size()));
}
}
Executing the above program outputs:
Age List: [10, 12, 15, 19, 23, 34]
Under 18: [10, 12, 15]
Over 18: [19, 23, 34]
In the above example, we created an array named ages, and the subList() method split it into two arrays: one for ages under 18 and one for ages over 18.
Note that we used the ages.size() method to get the length of the array. For more information about the size() method, visit Java ArrayList size().