Java Reference
In-Depth Information
java.util.AbstractSequentialList<E>
java.util.LinkedList<E>
+LinkedList()
+LinkedList(c: Collection<? extends E>)
+addFirst(element: E): void
+addLast(element: E): void
+getFirst(): E
+getLast(): E
+removeFirst(): E
+removeLast(): E
Creates a default empty linked list.
Creates a linked list from an existing collection.
Adds the element to the head of this list.
Adds the element to the tail of this list.
Returns the first element from this list.
Returns the last element from this list.
Returns and removes the first element from this list.
Returns and removes the last element from this list.
F IGURE 20.6
LinkedList provides methods for adding and inserting elements at both ends of the list.
Listing 20.3 gives a program that creates an array list filled with numbers and inserts new
elements into specified locations in the list. The example also creates a linked list from the
array list and inserts and removes elements from the list. Finally, the example traverses the
list forward and backward.
L ISTING 20.3
TestArrayAndLinkedList.java
1 import java.util.*;
2
3 public class TestArrayAndLinkedList {
4 public static void main(String[] args) {
5 List<Integer> arrayList = new ArrayList<>();
6 arrayList.add( 1 ); // 1 is autoboxed to new Integer(1)
7 arrayList.add( 2 );
8 arrayList.add( 3 );
9 arrayList.add( 1 );
10 arrayList.add( 4 );
11 arrayList.add( 0 , 10 );
12 arrayList.add( 3 , 30 );
13
14 System.out.println( "A list of integers in the array list:" );
15 System.out.println(arrayList);
16
17 LinkedList<Object> linkedList = new LinkedList<>(arrayList);
18 linkedList.add( 1 , "red" );
19 linkedList.removeLast();
20 linkedList.addFirst( "green" );
21
22 System.out.println( "Display the linked list forward:" );
23 ListIterator<Object> listIterator = linkedList.listIterator();
24 while (listIterator.hasNext()) {
25 System.out.print(listIterator.next() + " " );
26 }
27 System.out.println();
28
29 System.out.println( "Display the linked list backward:" );
30 listIterator = linkedList.listIterator(linkedList.size());
31 while (listIterator.hasPrevious()) {
32 System.out.print(listIterator.previous() + " " );
33 }
34 }
35 }
array list
linked list
list iterator
list iterator
 
 
Search WWH ::




Custom Search