Java Examples - Get the first and last elements of a linked list (LinkedList)

Java 实例Java Examples

The following example demonstrates how to use the linkedlistname.getFirst() and linkedlistname.getLast() methods of the LinkedList class to get the first and last elements of a 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 running the above code is:

链表的第一个元素是:100
链表的最后一个元素是:500

Java 实例Java Examples

Other extensions