Java Example – Removing Array Elements
Java arrays have a fixed length and cannot be deleted directly. We can create a new array and place the elements to be kept from the original array into the new array:
Main.java File
import
java
.
util
.
Arrays
;
public
class
RunoobTest
{
public
static
void
main
(
String
[
]
args
)
{
int
[
]
oldarray
=
new
int
[
]
{
3
,
4
,
5
,
6
,
7
}
;
//
Original array
int
num
=
2
;
//
Remove the element at index 2, i.e., remove the third element 5
int
[
]
newArray
=
new
int
[
oldarray
.
length
1
]
;
//
New array, with length equal to the original array minus 1
for
(
int
i
=
0
;
i
<
newArray
.
length
;
i
++
)
{
//
Check whether the element is out of bounds
if
(
num
<
0
||
num
=
oldarray.
length
)
{
throw
new
RuntimeException
(
"
Element out of bounds...
"
)
;
}
//
if
(
i
<
num
)
{
newArray
[
i
]
=
oldarray
[
i
];
}
else
{
newArray
[
i
]
=
oldarray
[
i
1
]
;
}
}
//
Print the array contents
System
.
out
.
println
(
Arrays
.
toString
(
oldarray
)
)
;
oldarray
=
newArray
;
System
.
out
.
println
(
Arrays
.
toString
(
oldarray
)
)
;
}
}
The output of the above code is:
[3, 4, 5, 6, 7]
[3, 4, 6, 7]
We can also use ArrayList to achieve this; ArrayList is a dynamic array and is more convenient to use.
The following example demonstrates how to use the remove() method of ArrayList to remove elements from the array list:
Main.java File
import
java
.
util
.
ArrayList
;
public
class
Main
{
public
static
void
main
(
String
[
]
args
)
{
ArrayList
<
String
objArray
=
new
ArrayList
<
String
(
);
objArray
.
clear
(
)
;
objArray
.
add
(
0
,
"
The 0th element
"
)
;
objArray
.
add
(
1
,
"
The 1st element
"
)
;
objArray
.
add
(
2
,
"
The 2nd element
"
)
;
System
.
out
.
println
(
"
Before removing array elements:
"
objArray
)
;
objArray
.
remove
(
1
)
;
objArray
.
remove
(
"
The 0th element
"
)
;
System
.
out
.
println
(
"
After removing array elements:
"
objArray
)
;
}
}
The output of the above code is:
数组删除元素前:[第 0 个元素, 第 1 个元素, 第 2 个元素]
数组删除元素后:[第 2 个元素]
Java Examples