Java ArrayList subList() Method
Example
Get a sublist from a list:
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<String> cars = new ArrayList<String>();
cars.add("Volvo");
cars.add("BMW");
cars.add("Ford");
cars.add("Mazda");
System.out.println( cars.subList(1, 3) );
}
}
Definition and Usage
The subList()
method returns a new list (referred to as a sublist) which contains the items of the list between two indices.
Note: The item at the last index is not included in the sublist.
Note: The sublist is a view of the original list, which means that changing the sublist also changes the original list.
Syntax
public List sublist(int start, int end)
Parameter Values
Parameter | Description |
---|---|
start | Required. The index where the sublist starts. |
end | Required. The index where the sublist ends. The item at this position is not included in the sublist. |
Technical Details
Returns: | A new List containing elements of the list. |
---|---|
Throws: |
IndexOutOfBoundsException - If one of the indices is less than zero or greater than the size of the list.IllegalArgumentException - If end index is less than the start index. |
More Examples
Example
A list can be changed by changing a sublist:
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
ArrayList<String> cars = new ArrayList<String>();
cars.add("Volvo");
cars.add("BMW");
cars.add("Ford");
cars.add("Mazda");
List<String> sublist = cars.subList(1, 3);
sublist.set(0, "Toyota");
System.out.println(cars);
}
}
Related Pages
❮ ArrayList Methods