Lists and the Collection Interface Chapter 4

Download Report

Transcript Lists and the Collection Interface Chapter 4

Lists and the Collection Interface
Chapter 4
Chapter Objectives
• To become familiar with the List interface
• To understand how to write an array-based
implementation of the List interface
• To study the difference between single-, double-, and
circular linked list data structures
• To learn how to implement the List interface using a
linked-list
• To understand the Iterator interface
Chapter 4: Lists and the Collection Interface
2
Chapter Objective (continued)
• To learn how to implement the iterator for a linked list
• To become familiar with the Java Collection framework
Chapter 4: Lists and the Collection Interface
3
The List Interface and ArrayList Class
• An array is an indexed structure: can select its elements
in arbitrary order using a subscript value
• Elements may be accessed in sequence using a loop
that increments the subscript
• Disadvantages of arrays: You cannot
• Increase or decrease the length
• Add an element at a specified position without shifting
the other elements to make room
• Remove an element at a specified position without
shifting other elements to fill in the resulting gap
Chapter 4: Lists and the Collection Interface
4
The List Interface and ArrayList Class
(continued)
• Allowed operations on the List interface include:
• Finding a specified target
• Adding an element to either end
• Removing an item from either end
• Traversing the list structure without a subscript
• Not all classes perform the allowed operations with the
same degree of efficiency
• An array provides the ability to store primitive-type data
whereas the List classes all store references to Objects.
Autoboxing facilitates this.
Chapter 4: Lists and the Collection Interface
5
The List Interface and ArrayList Class
(continued)
Chapter 4: Lists and the Collection Interface
6
The ArrayList Class
• Simplest class that implements the List interface
• “Improvement” over an array object
• Used when a programmer wants to add new elements to
the end of a list but still needs the capability to access the
elements stored in the list in arbitrary order
• For example:
List<String> myList = new ArrayList<String>();
myList.add(“Bashful”);
myList.add(“Awful”);
myList.add(“Jumpy”);
myList.add(“Happy”);
Chapter 4: Lists and the Collection Interface
7
The ArrayList Class
• Then
• After myList.add(2, “Doc”);
• After myList.add(“Dopey”);
Chapter 4: Lists and the Collection Interface
8
The ArrayList Class (continued)
• Suppose we have
• Then myList.remove(1);
• And myList.set(2, “Sneezy”);
Chapter 4: Lists and the Collection Interface
9
Generic Collections
• Language feature introduced in Java 5.0 called generic
collections (or generics)
• Generics allow you to define a collection that contains
references to objects of one specific type
•
List<String> myList = new ArrayList<String>();
specifies that myList is a List of String where String is a
type parameter
• Only references to objects of type String can be stored in
myList, and all items retrieved are of type String.
• A type parameter is analogous to a method parameter.
Chapter 4: Lists and the Collection Interface
10
Generic Collections
• In Java, a non-generic collection is more general than a
generic collection
• Non-generic collection can store objects of different data
types
• In a generic collection, all objects must be of same type
Chapter 4: Lists and the Collection Interface
11
Creating a Generic Collection
Chapter 4: Lists and the Collection Interface
12
Non-generic Example
• For example
ArrayList yourList = new ArrayList();
yourList.add(new Integer(35));// element 0 is Integer
yourList.add(“bunny”); // element 1 is String
yourList.add(new Double(3.14));// element 2 is Double
• Will this work?
String animal = yourList.get(1);
•
•
•
•
Syntax error: incompatible types, since it is an Object
Must cast: String animal = (String) yourList.get(1);
Consider: String aTwo = (String) yourList.get(2);
Will compile, but gives runtime error…
• This is bad!
Chapter 4: Lists and the Collection Interface
13
Generics
• Advantages include…
• Type incompatibility detected at compile time
• Downcasting not necessary
• Specific data types (e.g., String), not Object
• The book likes generics
• Book suggests you only use non-generics if need to
store objects of different types in same collection
Chapter 4: Lists and the Collection Interface
14
Specification of the ArrayList Class
Chapter 4: Lists and the Collection Interface
15
Application of ArrayList
• The ArrayList gives you additional capability beyond
what an array provides
• Combining Autoboxing with Generic Collections you can
store and retrieve primitive data types when working with
an ArrayList
• Section 4.2 gives some examples
• Phone Directory using ArrayList instead of array
• Read Section 4.2
• It’s only 2 pages!
Chapter 4: Lists and the Collection Interface
16
KWArrayList Class
• Authors implement their our own ArrayList class
• Call it KWArrayList
• Why are they doing this?
• Illustrates how class actually works (not in every
detail, but the basic ideas)
• Can analyze the work involved
• This work is all hidden when using ArrayList
Chapter 4: Lists and the Collection Interface
17
KWArrayList Class
• KWArrayList is author’s implementation of an ArrayList
class
• Physical size of array indicated by data field capacity
• Number of data items indicated by the data field size
Chapter 4: Lists and the Collection Interface
18
KWArrayList Class Definition
public class KWArrayList < E > {
// Data Fields
/** The default initial capacity */
private static final int INITIAL_CAPACITY = 10; /** The underlying
data array */
private E[] theData;
/** The current size */
private int size = 0;
/** The current capacity */
private int capacity = 0;
.....
Chapter 4: Lists and the Collection Interface
19
KWArrayList Class Constructor
public KWArrayList() {
capacity = INITIAL_CAPACITY;
theData = (E[]) new Object[capacity];
}
• Note that theData = (E[]) new Object[capacity]; causes
compiler to issue warning message:
KWListArray.java uses unchecked or unsafe operations
• Why?
Chapter 4: Lists and the Collection Interface
20
KWArrayList Class Constructor (Again)
public KWArrayList() {
capacity = INITIAL_CAPACITY;
theData = (E[]) new Object[capacity];
}
• Suppose that instead we use
theData = new E[capacity];
• Will this work?
• No, since type of E is not known at compile time, so
must create general Object and downcast
Chapter 4: Lists and the Collection Interface
21
Add(E anEntry) Method
• The algorithm…
• Insert new item at position indicated by size
• Increment the value of size
• Return true to indicate success
• The picture…
Chapter 4: Lists and the Collection Interface
22
Add(E anEntry) Method
• The code…
public boolean add(E anEntry) {
if (size == capacity) {
reallocate();
}
theData[size] = anEntry;
size++;
return true;
}
• Would this work?
theData[size++] = anEntry;
Chapter 4: Lists and the Collection Interface
23
Add(int index, E anEntry) Method
• The algorithm…
• Make room by shifting data elements “up”
• Insert anEntry at position index
• The picture…
Chapter 4: Lists and the Collection Interface
24
Add(int index, E anEntry) Method
• The code…
public void add(int index, E anEntry) {
if (index < 0 || index > size) {
throw new ArrayIndexOutOfBoundsException(index);
}
if (size == capacity) {
reallocate();
}
for (int i = size; i > index; i--) {
theData[i] = theData[i - 1];
}
theData[index] = anEntry;
size++;
}
Chapter 4: Lists and the Collection Interface
25
set Method
• The algorithm and picture are fairly obvious…
• The code…
public E set(int index, E newValue) {
if (index < 0 || index >= size) {
throw new ArrayIndexOutOfBoundsException(index);
}
E oldValue = theData[index];
theData[index] = newValue;
return oldValue;
}
Chapter 4: Lists and the Collection Interface
26
get Method
• The algorithm and picture are even more obvious…
• The code…
public E get(int index) {
if (index < 0 || index >= size) {
throw new ArrayIndexOutOfBoundsException(index);
}
return theData[index];
}
Chapter 4: Lists and the Collection Interface
27
remove Method
• The algorithm…
• Remove element
• Shift “down” to fill in the gap
• The picture…
Chapter 4: Lists and the Collection Interface
28
remove Method
• The code…
public E remove(int index) {
if (index < 0 || index >= size) {
throw new ArrayIndexOutOfBoundsException(index);
}
E returnValue = theData[index];
for (int i = index + 1; i < size; i++) {
theData[i - 1] = theData[i];
}
size--;
return returnValue;
}
Chapter 4: Lists and the Collection Interface
29
reallocate Method
• The algorithm…
• Double the size of the underlying array
• The picture…
• Not necessary!
• The code…
private void reallocate() {
capacity = 2 * capacity;
E[] newData = (E[]) new Object[capacity];
System.arraycopy(theData, 0, newData, 0, size);
theData = newData;
}
Chapter 4: Lists and the Collection Interface
30
KWArrayList as Collection of Objects
• Suppose we don’t want a generic collection…
public class KWArrayList {
// Data Fields
/** The default initial capacity */
private static final int INITIAL_CAPACITY = 10;
/** The current size */
private int size = 0;
.....
• And each reference to type E[] is now Object[]
/** The underlying data array */
private Object[] theData;
Chapter 4: Lists and the Collection Interface
31
Performance of KWArrayList
• Set and get methods execute in constant time
• No loops, so O(1)
• Inserting or removing elements is linear time
• Shift (at most) n elements, so O(n)
• What about reallocate?
Chapter 4: Lists and the Collection Interface
32
Vector Class
• Initial release of Java API contained the Vector class
which has similar functionality to the ArrayList
• Both contain the same methods
• New applications should use ArrayList rather than Vector
• The Stack class is a subclass of Vector
• But Stack class is actually useful (next chapter…)
Chapter 4: Lists and the Collection Interface
33
ArrayList Limitation
• Suppose we have a (virtual) line of 4 students
• Give each student a number, 0 thru 3
• Where number represents position in line
• For example: Bob (0), Alice (1), Eve (2), Charlie (3)
• Suppose Alice leaves
• Then Eve and Charlie must be “renumbered”
• In general, this is O(n) operation
• This is what happens with ArrayList remove
• Behind the scenes, of course
• Is there a better way?
Chapter 4: Lists and the Collection Interface
34
Linked Lists
• Again, suppose we have a (virtual) line of 4 students
• Instead of numbering…
• Tell each student who is behind them
• For example: Bob  Alice  Eve  Charlie
• Bob knows Alice is behind him, etc.
• Now suppose Alice leaves the line
• Only Bob needs to make a change
• Bob  Eve  Charlie
• How to implement this linked list data structure?
Chapter 4: Lists and the Collection Interface
35
Linked Lists
• The ArrayList add and remove methods operate in linear
time because loop shift elements in an array
• Linked list overcomes this by providing ability to add
or remove items anywhere in the list in constant time
• Each element (node) in a linked list stores information
and a link to the next node
• This is known as a single-linked list
• In a double-linked list, each node has a link to the next
node and a link to the previous node
Chapter 4: Lists and the Collection Interface
36
List Node
• A node contains a data item and one or more links
• A link is a reference to a node
• A node class generally defined inside another class
• Inner class: node details should be private
• Recall, private is visible to parent class
Chapter 4: Lists and the Collection Interface
37
Linked List: Insert
• Suppose we want to insert “Bob” after “Harry”
• First, set next of Bob to next of Harry
• Second, change Harry’s next to point to Bob
• Note that the order matters!
Chapter 4: Lists and the Collection Interface
38
Linked List: Remove
• Suppose we want to remove “Dick” from the list
• First, note that Tom comes before Dick in list
• Second, change next of Tom to next of Dick
• Note that we must know predecessor of Dick
Chapter 4: Lists and the Collection Interface
39
Traversing a Linked List
•
•
•
A fairly simple process:
1. Set nodeRef to reference of first node (head)
2. while nodeRef is not null
3.
do something with node referenced by nodeRef
4.
Set nodeRef to nodeRef.next
At end of list, nodeRef = nodeRef.next;
• Gives null, which is just fine
If you then execute this statement again, what happens?
• The dreaded NullPointerException
• You have fallen off the end of the linked list!
Chapter 4: Lists and the Collection Interface
40
Circular Linked List
• No beginning and no end
• Kinda like trying to graduate from SJSU…
• How to create a circular linked list?
• Set next of last element to point to first element
• Advantage(s)?
• Cannot fall off the end of the list
• Disadvantage(s)?
• Possible infinite loop
Chapter 4: Lists and the Collection Interface
41
Double-Linked Lists
• Limitations of a single-linked list include:
• Insertion at the front of the list is O(1).
• Insertion at other positions is O(n) where n is the size
of the list.
• Can insert a node only after a referenced node
• Can remove a node only if we have a reference to its
predecessor node
• Can traverse the list only in the forward direction
• These limitations are eliminated by adding a reference in
each node to the previous node: double-linked list
Chapter 4: Lists and the Collection Interface
42
Double-Linked List: Example
Chapter 4: Lists and the Collection Interface
43
Double-Linked List: Insert
• We want to insert Sharon between Harry and Sam
• Set Sharon’s next to Sam
• Set Sharon’s prev to Harry
• Set next of Harry to Sharon
• Set prev of Sam to Sharon
Chapter 4: Lists and the Collection Interface
44
Double-Linked List: Insert
Chapter 4: Lists and the Collection Interface
45
Double-Linked List: Insert
Chapter 4: Lists and the Collection Interface
46
Double-Linked List: Insert (Again)
• We want to insert Sharon into list before Sam…
• …only using references to Sam
• Set sharon.next to sam
• Set sharon.prev to sam.prev
• Set sam.prev.next to sharon
• Set sam.prev to sharon
• Note that the order matters!
• Must use sam.prev before changing it
Chapter 4: Lists and the Collection Interface
47
Double-Linked List: Insert (Again)
Chapter 4: Lists and the Collection Interface
48
Double-Linked List: Insert (Again)
Chapter 4: Lists and the Collection Interface
49
Double-Linked List: Remove
• Suppose we want to remove Harry
• Where Harry is after Dick and before Sharon
• Set dick.next to sharon
• Set sharon.prev to dick
Chapter 4: Lists and the Collection Interface
50
Double-Linked List: Remove (Again)
• Suppose we want to remove Harry…
• …using only references to Harry
• Set harry.prev.next to harry.next
• Set harry.next.prev to harry.prev
Chapter 4: Lists and the Collection Interface
51
Circular Lists
• Circular Single-Linked List
• Link last node to the first node
• That is, tail.next = head;
• Circular Double-Linked List
• Link last node to the first node and the first to the last
• I.e., head.prev = tail; and tail.next = head;
• Advantage: can traverse in forward or reverse direction
even after you have passed the last or first node
• Can visit all the list elements from any starting point
• Can never fall off the end of a list
• Disadvantage: infinite loop!
Chapter 4: Lists and the Collection Interface
52
Circular Double-Linked List
Chapter 4: Lists and the Collection Interface
53
LinkedList<E> Class
• Part of Java API
• Package java.util
• Implements the List<E> interface using a double-linked
list
• Contains many of same methods as ArrayList
• Also some methods not in ArrayList
Chapter 4: Lists and the Collection Interface
54
LinkedList<E> Class
Chapter 4: Lists and the Collection Interface
55
Accessing LinkedList Elements
• How to access each element in a LinkedList?
• This will work:
for
(int index = 0; index < aList.size(); index++) {
E nextElement =
aList.get(index);
...
}
•
•
•
•
•
Work appears to be linear, or O(n)
But, internally, what does get do?
It starts at 0 and goes to index
Then actual work is quadratic, or O(n2)
Can we do this more efficiently?
Chapter 4: Lists and the Collection Interface
56
Iterator<E> Interface
•
•
Iterator defined in package java.util
List interface declares the method iterator
• Returns an Iterator object
• Iterates over the elements of the list
• Note that iterator points “between” nodes
• Use Iterator’s next method to retrieve next element
• Iterator similar to StringTokenizer object
Chapter 4: Lists and the Collection Interface
57
Iterator<E> Interface
• Suppose iter declared an Iterator for myList
• Where myList is a LinkedList
• Then can access each element using
while (iter.hasNext()) {
E nextElement = iter.next();
...
}
• How much work is this?
• Appears to be O(n)…and it really is!
• How to declare an Iterator object?
Chapter 4: Lists and the Collection Interface
58
Iterator<E> Interface
• Here, we process elements of List<Integer> aList using
the Iterator object itr
Iterator<Integer> itr = aList.iterator();
while (itr.hasNext()) {
int value = itr.next();
...
}
• Again, Iterator object does not point to an element
• Instead, points “between” elements
Chapter 4: Lists and the Collection Interface
59
Iterator<E> Interface
Chapter 4: Lists and the Collection Interface
60
Iterator<E> and remove Method
• Each call to remove must be preceded by next
• Use Iterator.remove instead of List.remove
• For example, to remove all elements divisible by div…
public static void remDiv(LinkedList<Integer> aList,
int div) {
Iterator<Integer> iter = aList.iterator();
while (iter.hasNext()) {
int nextInt = iter.next();
if (nextInt % div == 0)
iter.remove();
}
}
Chapter 4: Lists and the Collection Interface
61
ListIterator<E> Interface
•
Iterator limitations
• Can only traverse the List in the forward direction
• Provides remove method, but no add method
• Must manually advance Iterator to start of list
• ListIterator<E> extends Iterator<E> interface
• And it overcomes above limitations
• As with Iterator, a ListIterator lives “between” elements of
the linked list
Chapter 4: Lists and the Collection Interface
62
ListIterator<E> Interface
Chapter 4: Lists and the Collection Interface
63
ListIterator<E> Interface
• Create ListIterator starting between elements 2 and 3
ListIterator<String> myIter = myList.listIterator(3);
• Then myIter.next() returns ref to string at position 3
• What do these do?
myIter.nextIndex() and myIter.previousIndex()
myIter.previous()
myIter.hasNext() and myIter.hasPrevious()
Chapter 4: Lists and the Collection Interface
64
ListIterator<E> Interface
• To search for first occurrence of target and replace with
newItem could use the following…
ListIterator<String> myIter = myList.listIterator();
while (myIter.hasNext()) {
if (target.equals(myIter.next()))
myIter.set(newItem);
break;
}
}
• Can we use Iterator instead?
Chapter 4: Lists and the Collection Interface
65
Comparison of Iterator and ListIterator
•
ListIterator<E> is a subinterface of Iterator<E>
• So, classes that implement ListIterator have both
• Iterator interface requires fewer methods and can be
used to iterate over more general data structures
• But only in one direction
• Iterator is required by the Collection interface
• ListIterator is required only by the List interface
Chapter 4: Lists and the Collection Interface
66
ListIterator and Index
•
•
ListIterator has the methods nextIndex and previousIndex
• Return index value of next or previous
LinkedList has method listIterator(int index)
• Returns ListIterator that gives next
• However, this ListIterator starts at beginning
• In general, not as efficient as “real” ListIterator
Chapter 4: Lists and the Collection Interface
67
Enhanced for Statement
• Aka “for each” statement
• Makes it easier to use iterators
• Creates Iterator, implicitly calls hasNext and next
• Other Iterator methods (remove) not available
• For example,
sum = 0;
for (int nextInt: aList) {
sum += nextInt;
}
• Can also use “for each” with arrays
Chapter 4: Lists and the Collection Interface
68
The Enhanced for Statement
Chapter 4: Lists and the Collection Interface
69
Iterable Interface
• Requires only that a class that implements it provide an
iterator method
• The Collection interface extends the Iterable interface,
so all classes that implement the List interface must
provide an iterator method
Chapter 4: Lists and the Collection Interface
70
Implementation of a Double-Linked List
• Call it KWLinkedList
• Why “KW”?
• A “homebrew” double-linked list and iterator
• Not a complete implementation
• For illustration purposes only
• You should not use KWLinkedList in real applications
• Recall KWArrayList
• Illustrated underlying role of arrays in ArrayList
• Somewhat similar goal here…
Chapter 4: Lists and the Collection Interface
71
KWLinkedList Data Fields
import java.util.*;
/** KWLinkedList implements a double-linked list */
public class KWLinkedList < E > {
// Data Fields
/** A reference to the head of the list. */
private Node < E > head = null;
/** A reference to the end of the list. */
private Node < E > tail = null;
/** The size of the list. */
private int size = 0;
Chapter 4: Lists and the Collection Interface
72
KWLinkedList Data Fields
Chapter 4: Lists and the Collection Interface
73
KWLinkedList Methods
• add(int index, E obj)
• get(int index)
• listIterator(int index)
Chapter 4: Lists and the Collection Interface
74
KWLinkedList Methods
add(int index, E obj)
• Obtain reference to node at position index
• Insert new node containting obj before position index
get(int index)
• Obtain reference to node at position index
• Return contents of node at position index
listIterator(int index)
• Obtain reference to node at position index
• Create ListIterator positioned just before index
Chapter 4: Lists and the Collection Interface
75
KWLinkedList Methods
• All 3 methods have same first step
• So use one method in each case
• Also, ListIterator has an add method
• Inserts new item before current position
• So, we will use ListIterator to implement add…
add(int index, E obj)
• Obtain iterator positioned just before position index
• Insert new node containing obj before iterator
Chapter 4: Lists and the Collection Interface
76
KWLinkedList add Method
/** Add an item at the specified index. */
public void add(int index, E obj) {
listIterator(index).add(obj);
}
• Note it’s not necessary to declare local ListIterator
• Use an anonymous ListIterator object
Chapter 4: Lists and the Collection Interface
77
KWLinkedList get Method
/** Get the element at position index. */
public E get(int index) {
return listIterator(index).next();
}
• Other methods:
• addFirst, addLast, getFirst, getLast
• These can be implemented by delegation to add and get
methods, above
Chapter 4: Lists and the Collection Interface
78
KWListIter Class
• Class KWListIter implement the ListIterator interface
• An inner class of KWLinkedList
• Can access data fields and members of parent class
• Data fields…
/** Inner class to implement ListIterator interface. */
private class KWListIter implements ListIterator < E > {
/** A reference to the next item. */
private Node < E > nextItem;
/** A reference to the last item returned. */
private Node < E > lastItemReturned;
/** The index of the current item. */
private int index = 0;
Chapter 4: Lists and the Collection Interface
79
KWListIter Data Fields
Chapter 4: Lists and the Collection Interface
80
KWListIter Constructor
public KWListIter(int i) {
// Validate i parameter.
if (i < 0 || i > size) {
throw new IndexOutOfBoundsException(
"Invalid index " + i);
}
lastItemReturned = null; // No item returned yet.
// Special case of last item.
if (i == size) {
index = size;
nextItem = null;
} else { // Start at the beginning
nextItem = head;
for (index = 0; index < i; index++) {
nextItem = nextItem.next;
}
}
}
Chapter 4: Lists and the Collection Interface
81
KWListIter hasNext Method
/** Indicate whether movement forward is defined.
@return true if call to next will not throw an exception
*/
public boolean hasNext() {
return nextItem != null;
}
Chapter 4: Lists and the Collection Interface
82
KWListIter next Method
/** Move the iterator forward and return the next item.
@return The next item in the list
@throws NoSuchElementException if there is no such object
*/
public E next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
lastItemReturned = nextItem;
nextItem = nextItem.next;
index++;
return lastItemReturned.data;
}
Chapter 4: Lists and the Collection Interface
83
KWLinkedList and KWListIter Example
Chapter 4: Lists and the Collection Interface
84
Advancing KWListIter
Chapter 4: Lists and the Collection Interface
85
KWListIter hasPrevious Method
/** Indicate whether movement backward is defined.
@return true if call to previous will not throw an
exception
*/
public boolean hasPrevious() {
return (nextItem == null && size != 0)
||
nextItem.prev != null;
}
Chapter 4: Lists and the Collection Interface
86
KWListIter previous Method
public E previous() {
if (!hasPrevious()) {
throw new NoSuchElementException();
}
if (nextItem == null) { // past last
nextItem = tail;
} else {
nextItem = nextItem.prev;
}
lastItemReturned = nextItem;
index--;
return lastItemReturned.data;
}
Chapter 4: Lists and the Collection Interface
87
KWListIter add Method
• Inserts new node before nextItem
• Four cases to consider…
• Add to an empty list
• Then head is null
• Add to head of list
• Then nextItem is head
• Add to tail of list
• Then nextItem is null
• Add to middle of list
• All other cases
Chapter 4: Lists and the Collection Interface
88
add to Empty List
public void add(E obj) {
if (head == null) { // Add to empty list.
head = new Node < E > (obj);
tail = head;
}
Chapter 4: Lists and the Collection Interface
89
add to Empty List
Chapter 4: Lists and the Collection Interface
90
add to Head of List
else if (nextItem == head) { // Insert at head
// Create a new node.
Node < E > newNode = new Node < E > (obj);
// Link it to the nextItem.
newNode.next = nextItem; // Step 1
// Link nextItem to the new node.
nextItem.prev = newNode; // Step 2
// The new node is now the head.
head = newNode; // Step 3
}
Chapter 4: Lists and the Collection Interface
91
add to Head of List
Chapter 4: Lists and the Collection Interface
92
add to Tail of List
else if (nextItem == null) {// Insert tail
// Create a new node
Node < E > newNode = new Node < E > (obj);
// Link the tail to the new node.
tail.next = newNode; // Step 1
// Link the new node to the tail. newNode.prev = tail; //
Step 2
// The new node is the new tail.
tail = newNode; // Step 3
}
Chapter 4: Lists and the Collection Interface
93
add to Tail of List
Chapter 4: Lists and the Collection Interface
94
add to Middle of List
else { // Insert into the middle.
// Create a new node.
Node < E > newNode = new Node < E > (obj);
// Link it to nextItem.prev.
newNode.prev = nextItem.prev; // Step 1
nextItem.prev.next = newNode; // Step 2
// Link it to the nextItem.
newNode.next = nextItem; // Step 3
nextItem.prev = newNode; // Step 4
}
Chapter 4: Lists and the Collection Interface
95
add to Middle of List
Chapter 4: Lists and the Collection Interface
96
add … The Last Word
// Increase size, index, set lastItemReturned
size++;
index++;
lastItemReturned = null;
} // End of method add.
Chapter 4: Lists and the Collection Interface
97
Inner Classes
• Two inner classes in KWLinkedList<E>
• That is, Node<E> and KWListIter<E>
• Declare Node<E> to be static
• No need for its methods to access data fields of
parent class
• Cannot declare KWListIter<E> to be static
• Its methods access and modify fields of KWLinkedList
• Type parameter <E> is considered previously defined
• So, <E> cannot appear as part of class name
Chapter 4: Lists and the Collection Interface
98
Application of the LinkedList Class
• Case study that uses the Java LinkedList class to solve
a common problem: maintaining an ordered list
Chapter 4: Lists and the Collection Interface
99
Application of the LinkedList Class
(continued)
Chapter 4: Lists and the Collection Interface
100
Application of the LinkedList Class
(continued)
Chapter 4: Lists and the Collection Interface
101
The Collection Hierarchy
• Both the ArrayList and LinkedList represent a collection
of objects that can be referenced by means of an index
• The Collection interface specifies a subset of the
methods specified in the List interface
Chapter 4: Lists and the Collection Interface
102
The Collection Hierarchy (continued)
Chapter 4: Lists and the Collection Interface
103
Common Features of Collections
• Collection interface specifies a set of common methods
• Fundamental features include:
• Collections grow as needed
• Collections hold references to objects
• Collections have at least two constructors
Chapter 4: Lists and the Collection Interface
104
Chapter Review
• The List is a generalization of the array
• The Java API provides the ArrayList class, which uses
an array as the underlying structure to implement the List
• A linked list consists of a set of nodes, each of which
contains its data and a reference to the next node
• To find an item at a position indicated by an index in a
linked list requires traversing the list from the beginning
until the item at the specified index is found
• An iterator gives with the ability to access the items in a
List sequentially
Chapter 4: Lists and the Collection Interface
105
Chapter Review (continued)
• The ListIterator interface is an extension of the Iterator
interface
• The Java API provides the LinkedList class, which uses
a double-linked list to implement the List interface
• The Iterable interface is the root of the Collection
hierarchy
• The Collection interface and the List interface define a
large number of methods that make these abstractions
useful for many applications
Chapter 4: Lists and the Collection Interface
106