/** * Java Collections Framework > LinkedListExample.java * * Use a LinkedList to store objects. A LinkedList grows dynamically as * you add objects to it; it also shrinks dynamically when you remove objects * from it. A LinkedList is very similar to an ArrayList; the difference is * that LinkedList has an additional set of methods that can get, remove, * and insert at the front and back of the list. Because of this, a * LinkedList may be used as a stack, queue, or double-ended queue (also * known as a deque). * * @author Feihong Hsu */ import java.util.LinkedList; // A growable array public class LinkedListExample { // This method prints the elements of the given LinkedList. public static void printLinkedList(LinkedList list) { System.out.print( "LinkedList: " ); // If the list is not empty, print a comma-delimited list of all the // elements. Otherwise just print "empty". if (!list.isEmpty()) { for (int i=0; i < list.size(); i++) System.out.print( list.get(i) + ", " ); System.out.println(); } else System.out.println( "empty" ); } public static void main(String[] args) { LinkedList list = new LinkedList(); // Add 5 objects to the LinkedList. list.add("Popcorn"); list.add(new Double(63.0)); list.add(new StringBuffer("Butter")); list.add(new Integer(923)); list.add(new java.awt.Point(3, 6)); // "LinkedList: Popcorn, 63.0, Butter, 923, java.awt.Point[x=3,y=6]" printLinkedList(list); // Remove the first element from the LinkedList. list.removeFirst(); // "LinkedList: 63.0, Butter, 923, java.awt.Point[x=3,y=6]," printLinkedList(list); // Remove the last element from the LinkedList. list.removeLast(); // "LinkedList: 63.0, Butter, 923," printLinkedList(list); // Add an object to the front of the LinkedList. list.addFirst(new Long(788L)); // "LinkedList: 788, 63.0, Butter, 923," printLinkedList(list); // Add an object to the back of the LinkedList. list.addLast(new Character('X')); // "LinkedList: 788, 63.0, Butter, 923, X," printLinkedList(list); // Print the first element of the LinkedList - "First element: 788" System.out.println( "First element: " + list.getFirst() ); // Print the last element of the LinkedList - "Last element: X" System.out.println( "Last element: " + list.getLast() ); } } /* Output: LinkedList: Popcorn, 63.0, Butter, 923, java.awt.Point[x=3,y=6], LinkedList: 63.0, Butter, 923, java.awt.Point[x=3,y=6], LinkedList: 63.0, Butter, 923, LinkedList: 788, 63.0, Butter, 923, LinkedList: 788, 63.0, Butter, 923, X, First element: 788 Last element: X */