ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
# Java - 在`LinkedList`的开头和结尾添加元素 > 原文: [https://beginnersbook.com/2014/07/java-add-elements-at-beginning-and-end-of-linkedlist-example/](https://beginnersbook.com/2014/07/java-add-elements-at-beginning-and-end-of-linkedlist-example/) #### 示例 在这个例子中,我们将学习如何在`LinkedList`的开头和结尾添加元素。我们将使用`LinkedList`类的[`addFirst()`](https://docs.oracle.com/javase/7/docs/api/java/util/LinkedList.html#addFirst(E))和[`addLast()`方法](https://docs.oracle.com/javase/7/docs/api/java/util/LinkedList.html#addLast(E))。方法定义和描述如下: 1)`public void addFirst(E e)`:在此列表的开头插入指定的元素。 2)`public void addLast(E e)`:将指定的元素追加到此列表的末尾。 **完整代码:** ```java import java.util.LinkedList; public class AddExample { public static void main(String[] args) { // Creating LinkedList of String Elements LinkedList<String> linkedlist = new LinkedList<String>(); //Populating it with String values linkedlist.add("AA"); linkedlist.add("BB"); linkedlist.add("CC"); linkedlist.add("DD"); linkedlist.add("EE"); //Displaying LinkedList elements System.out.println(linkedlist); //Adding an element at the beginning linkedlist.addFirst("FIRST"); //Displaying the List after addition System.out.println(linkedlist); //Adding an element at the end of list linkedlist.addLast("LAST"); //Displaying the final list System.out.println(linkedlist); } } ``` 输出: ```java [AA, BB, CC, DD, EE] [FIRST, AA, BB, CC, DD, EE] [FIRST, AA, BB, CC, DD, EE, LAST] ```