Java Example – Getting the First and Last Elements of a LinkedList
The following example demonstrates how to use the getFirst() and getLast() methods of the LinkedList class to get the first and last elements of the linked list:
Main.java File
import
java
.
util
.
LinkedList
;
public
class
Main
{
public
static
void
main
(
String
[
]
args
)
{
LinkedList
<
String
lList
=
new
LinkedList
<
String
(
);
lList
.
add
(
"
100
"
)
;
lList
.
add
(
"
200
"
)
;
lList
.
add
(
"
300
"
)
;
lList
.
add
(
"
400
"
)
;
lList
.
add
(
"
500
"
)
;
System
.
out
.
println
(
"
The first element of the linked list is:
"
lList
.
getFirst
(
)
)
;
System
.
out
.
println
(
"
The last element of the linked list is:
"
lList
.
getLast
(
)
)
;
}
}
The output of the above code is:
链表的第一个元素是:100
链表的最后一个元素是:500
Java Examples