Java ArrayList get() Method
The get() method obtains the element in the dynamic array by index value.
The syntax of the get() method is:
arraylist.get(int index)
**Note:** arraylist is an object of the ArrayList class.
Parameter Description:
- index - the index value.
Return Value
Returns the element at the specified index in the dynamic array.
If the index value is out of range, an IndexOutOfBoundsException is thrown.
Example
Using the get() method in an array of type String:
Example
import
java.util.ArrayList
;
class
Main
{
public
static
void
main
(
String
[
]
args
)
{
// Create an array
ArrayList
<
String
sites
=
new
ArrayList
<>
(
)
;
sites.
add
(
"Google"
)
;
sites.
add
(
"Runoob"
)
;
sites.
add
(
"Taobao"
)
;
System
.
out
.
println
(
"Website list: "
sites
)
;
// Get the element at index 1
String
element
=
sites.
get
(
1
)
;
System
.
out
.
println
(
"The element at index 1 is: "
element
)
;
}
}
The output of the above program is:
网站列表: [Google, Runoob, Taobao]
索引值为 1 的元素为: Runoob
In the example above, we created an array named sites and used the get() method to get the element at index 1.
A dynamic array of type Integer using the get() method:
Example
import
java.util.ArrayList
;
class
Main
{
public
static
void
main
(
String
[
]
args
)
{
// Create an array
ArrayList
<
Integer
numbers
=
new
ArrayList
<>
(
)
;
// Insert elements into the array
numbers.
add
(
22
)
;
numbers.
add
(
13
)
;
numbers.
add
(
35
)
;
System
.
out
.
println
(
"Numbers ArrayList: "
numbers
)
;
// Get the element at position index 2
int
element
=
numbers.
get
(
2
)
;
System
.
out
.
println
(
"The element at index 2 is: "
element
)
;
}
}
The output of the above program is:
Numbers ArrayList: [22, 13, 35]
索引值为 2 的元素为: 35
In the example above, the get() method is used to access the element at index 2.
**Note:** We can also use the indexOf() method to return the index value of an element in the ArrayList. To learn more, please visit Java ArrayList indexOf().
Java ArrayList