可以分别使用方法java.util.LinkedList.getFirst()和java.util.LinkedList.getLast()获得链接列表的第一个和最后一个元素。这些方法都不要求任何参数。
演示此程序如下
示例import java.util.LinkedList;
public class Demo {
public static void main(String[] args) {
LinkedList l = new LinkedList();
l.add("John");
l.add("Sara");
l.add("Susan");
l.add("Betty");
l.add("Nathan");
System.out.println("The first element of the Linked List is : " + l.getFirst());
System.out.println("The last element of the Linked List is : " + l.getLast());
}
}
上面程序的输出如下The first element of the Linked List is : John
The last element of the Linked List is : Nathan
现在让我们了解上面的程序。
LinkedList l被创建。然后,使用LinkedList.getFirst()和LinkedList.getLast()分别获取链接列表的第一个和最后一个元素。演示这的代码片段如下LinkedList l = new LinkedList();
l.add("John");
l.add("Sara");
l.add("Susan");
l.add("Betty");
l.add("Nathan");
System.out.println("The first element of the Linked List is : " + l.getFirst());
System.out.println("The last element of the Linked List is : " + l.getLast());