Java ArrayList subList() Method · Private Archive
Java ArrayList subList() Method
The subList() method is used to intercept and return a part of the dynamic array.
arraylist.subList(int fromIndex, int toIndex)
**Note:** arraylist is an object of the ArrayList class.
Parameter Description:
- The syntax of the subList() method is:
- fromIndex - the starting position for intercepting elements, including the element at this index position
Return Value
toIndex - the ending position for intercepting elements, not including the element at this index position
Returns the intercepted part of the given dynamic array.
If fromIndex is less than 0 or greater than the length of the array, an IndexOutOfBoundsException is thrown
If fromIndex is greater than toIndex, an IllegalArgumentException is thrown.

Example
Note: The dynamic array contains elements starting from the fromIndex position up to the element at index toIndex-1, and does not include the element at the toIndex position.
Example
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
(
"Runoob"
)
;
sites.
add
(
"Taobao"
)
;
sites.
add
(
"Wiki"
)
;
System
.
out
.
println
(
"Website list: "
sites
)
;
Intercepting a sublist from the dynamic array:
System
.
out
.
println
(
"SubList: "
sites.
subList
(
1
,
3
)
)
;
}
}
The output of the above program is:
网站列表: [Google, Runoob, Taobao, Wiki]
SubList: [Runoob, Taobao]
// Element positions 1 to 3
In the example above, we used the subList() method to get the elements at indices 1 to 3 (excluding 3).
Example
import
java.util.ArrayList
;
class
Main
{
public
static
void
main
(
String
[
]
args
)
{
// Create an array
ArrayList
<
Integer
ages
=
new
ArrayList
<>
(
)
;
Splitting a dynamic array into two dynamic arrays:
ages.
add
(
10
)
;
ages.
add
(
12
)
;
ages.
add
(
15
)
;
ages.
add
(
19
)
;
ages.
add
(
23
)
;
ages.
add
(
34
)
;
System
.
out
.
println
(
// Add some elements to the array
ages
)
;
"Age list: "
System
.
out
.
println
(
// Under 18
ages.
subList
(
0
,
3
)
)
;
"Under 18: "
System
.
out
.
println
(
// Over 18
ages.
subList
(
3
, ages.
size
(
)
)
)
;
}
}
The output of the above program is:
年龄列表: [10, 12, 15, 19, 23, 34]
18 岁以下: [10, 12, 15]
18 岁以上: [19, 23, 34]
"Over 18: "
In the example above, we created an array named ages; the subList() method splits this array into two arrays: ages under 18 and ages over 18.
Java ArrayList