Java ArrayList toArray() Method · Private Archive
Java ArrayList toArray() Method
The toArray() method converts an ArrayList object into an array.
arraylist.toArray(T[] arr)
**Note:** arraylist is an object of the ArrayList class.
Parameter Description:
- The syntax of the toArray() method is:
T [] arr (optional parameter) - the array used to store the array elements
Return Value
**Note:** Here T refers to the type of the array.
If the parameter T[] arr is passed into the method, an array of type T is returned.
Example
If no parameter is passed, an array of type Object is returned.
Example
import
java.util.ArrayList
;
import
java.util.Comparator
;
class
Main
{
public
static
void
main
(
String
[
]
args
)
{
// Create a dynamic array
ArrayList
<
String
sites
=
new
ArrayList
<>
(
)
;
sites.
add
(
"Runoob"
)
;
sites.
add
(
"Google"
)
;
sites.
add
(
"Wiki"
)
;
sites.
add
(
"Taobao"
)
;
System
.
out
.
println
(
"Website list: "
sites
)
;
Array parameter of a specified type:
// Create a new array of type String
String
[
]
arr
=
new
String
[
sites.
size
(
)
]
;
// The array length is the same as the ArrayList length
sites.
toArray
(
arr
)
;
// Convert the ArrayList object into an array
System
.
out
.
(
"Array: "
)
;
for
(
String
item
:
arr
)
{
System
.
out
.
(
item
", "
)
;
}
}
}
The output of the above program is:
网站列表: [Runoob, Google, Wiki, Taobao]
Array: Runoob, Google, Wiki, Taobao,
// Output all elements of the array
Note this line:
sites.toArray(arr);
In the example above, we used the sort() method on the array named sites.
Here, we passed an array of type String as a parameter, and all elements are stored in the string array. ArrayList size() **Note:** The length of the passed array parameter should be equal to or greater than the arraylist. Here, we used
the method to create an array of the same size as the arraylist.
Example
import
java.util.ArrayList
;
import
java.util.Comparator
;
class
Main
{
public
static
void
main
(
String
[
]
args
)
{
// Create a dynamic array
ArrayList
<
String
sites
=
new
ArrayList
<>
(
)
;
sites.
add
(
"Runoob"
)
;
sites.
add
(
"Google"
)
;
sites.
add
(
"Wiki"
)
;
sites.
add
(
"Taobao"
)
;
System
.
out
.
println
(
"Website list: "
sites
)
;
Using the toArray() method without parameters:
// Convert the ArrayList object into an array
Object
[
]
obj
=
sites.
toArray
(
)
;
// This method has no parameters
System
.
out
.
(
"Array: "
)
;
for
(
Object
item
:
obj
)
{
System
.
out
.
(
item
", "
)
;
}
}
}
The output of the above program is:
网站列表: [Runoob, Google, Wiki, Taobao]
Array: Runoob, Google, Wiki, Taobao,
// Output all elements in the array
In the example above, we used toArray() to convert the arraylist into an array.
Java ArrayList