Java 集合 将LinkedList添加到LinkedList的前面

将元素添加到链表的开始(头部)的程序。

程序

import java.util.LinkedList;
class LinkedListExample {

  public static void main(String[] args) {

     // create a LinkedList
     LinkedList<String> list = new LinkedList<String>();

     // Add elements
     list.add("AA");
     list.add("BB");
     list.add("CC");
     list.add("DD");

     // Display List element
     System.out.println("LinkedList Elements:"+list);

     // Adding element to front of LinkedList
     /* public boolean offerFirst(E e): Inserts the 
      * specified element at the front of this list.
      */
     list.offerFirst("NEW Element");

     // Displaying List after adding element
     System.out.println("LinkedList After Addition:"+list);
  }
}

输出:

LinkedList Elements:[AA, BB, CC, DD]
LinkedList After Addition:[NEW Element, AA, BB, CC, DD]
赞(0)

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

Java 集合