Java ArrayList removeRange() Method · Private Archive
Java ArrayList removeRange() Method
The removeRange() method is used to delete the elements that exist between specified indices.
arraylist.removeRange(int fromIndex, int toIndex)
**Note:** arraylist is an object of the ArrayList class.
Parameter Description:
- The syntax of the removeRange() method is:
- fromIndex - the starting position of the index, including the value at this index position
Return Value
No value is returned.
toIndex - the ending position of the index, not including the value at this index position
This method deletes only part of the dynamic array elements, from fromIndex to toIndex-1. That is, it does not include the element at the toIIndex index position. < Note: If fromIndex or toIndex index is out of range, or toIndex
Example
is greater than fromIndex, an IndexOutOfBoundException is thrown.
Example
import
java.util.*
;
class
Main
extends
ArrayList
<
String
{
public
static
void
main
(
String
[
]
args
)
{// Create a dynamic array
Main sites
=
new
Main
(
)
;
sites.
add
(
"Google"
)
;
sites.
add
(
"Runoob"
)
;
sites.
add
(
"Taobao"
)
;
sites.
add
(
"Wiki"
)
;
sites.
add
(
"Weibo"
)
;
System
.
out
.
println
(
"ArrayList : "
sites
)
;
The following example demonstrates the use of the removeRange() method:
sites.
removeRange
(
1
,
3
)
;
System
.
out
.
println
(
// Delete elements whose name contains Tao
sites
)
;
}
}
The output of the above program is:
ArrayList : [Google, Runoob, Taobao, Wiki, Weibo]
删除后的 ArrayList: [Google, Wiki, Weibo]
// Delete elements from index 1 to 3
The removeRange() method is protected, so to use it you need to extend the ArrayList class; after extending, we can use the Main class to create a dynamic array. ArrayList subList() and ArrayList clear() The removeRange() method is not commonly used; we usually can use
Example
import
java.util.ArrayList
;
class
Main
{
public
static
void
main
(
String
[
]
args
)
{
the method to delete elements.
ArrayList
<
Integer
numbers
=
new
ArrayList
<>
(
);
// Insert elements into the array
numbers.
add
(
1
)
;
numbers.
add
(
2
)
;
numbers.
add
(
3
)
;
numbers.
add
(
4
)
;
numbers.
add
(
6
)
;
System
.
out
.
println
(
"ArrayList: "
numbers
)
;
// Create an integer dynamic array
numbers.
subList
(
1
,
3
)
.
clear
(
)
;
System
.
out
.
println
(
"Updated ArrayList: "
numbers
)
;
}
}
The output of the above program is:
ArrayList: [1, 2, 3, 4, 6]
Updated ArrayList: [1, 4, 6]
// Delete all even elements
Note these expressions:
numbers.subList(1, 3).clear();
- subList(1, 3) // Delete elements at index positions 1 to 3
- clear() - Returns the elements with index values 1 and 2.
Java ArrayList