Lists and the Collection Interface Chapter 4 Chapter 4: Lists and the Collection Interface2 Chapter...
-
date post
20-Dec-2015 -
Category
Documents
-
view
246 -
download
0
Transcript of Lists and the Collection Interface Chapter 4 Chapter 4: Lists and the Collection Interface2 Chapter...
![Page 1: Lists and the Collection Interface Chapter 4 Chapter 4: Lists and the Collection Interface2 Chapter Objectives To become familiar with the List interface.](https://reader033.fdocuments.us/reader033/viewer/2022061614/56649d4d5503460f94a2c9a0/html5/thumbnails/1.jpg)
Lists and the Collection Interface
Chapter 4
![Page 2: Lists and the Collection Interface Chapter 4 Chapter 4: Lists and the Collection Interface2 Chapter Objectives To become familiar with the List interface.](https://reader033.fdocuments.us/reader033/viewer/2022061614/56649d4d5503460f94a2c9a0/html5/thumbnails/2.jpg)
Chapter 4: Lists and the Collection Interface 2
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
![Page 3: Lists and the Collection Interface Chapter 4 Chapter 4: Lists and the Collection Interface2 Chapter Objectives To become familiar with the List interface.](https://reader033.fdocuments.us/reader033/viewer/2022061614/56649d4d5503460f94a2c9a0/html5/thumbnails/3.jpg)
Chapter 4: Lists and the Collection Interface 3
Chapter Objective (continued)
• To learn how to implement the iterator for a linked list• To become familiar with the Java Collection framework
![Page 4: Lists and the Collection Interface Chapter 4 Chapter 4: Lists and the Collection Interface2 Chapter Objectives To become familiar with the List interface.](https://reader033.fdocuments.us/reader033/viewer/2022061614/56649d4d5503460f94a2c9a0/html5/thumbnails/4.jpg)
Chapter 4: Lists and the Collection Interface 4
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
![Page 5: Lists and the Collection Interface Chapter 4 Chapter 4: Lists and the Collection Interface2 Chapter Objectives To become familiar with the List interface.](https://reader033.fdocuments.us/reader033/viewer/2022061614/56649d4d5503460f94a2c9a0/html5/thumbnails/5.jpg)
Chapter 4: Lists and the Collection Interface 5
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.
![Page 6: Lists and the Collection Interface Chapter 4 Chapter 4: Lists and the Collection Interface2 Chapter Objectives To become familiar with the List interface.](https://reader033.fdocuments.us/reader033/viewer/2022061614/56649d4d5503460f94a2c9a0/html5/thumbnails/6.jpg)
Chapter 4: Lists and the Collection Interface 6
The List Interface and ArrayList Class (continued)
![Page 7: Lists and the Collection Interface Chapter 4 Chapter 4: Lists and the Collection Interface2 Chapter Objectives To become familiar with the List interface.](https://reader033.fdocuments.us/reader033/viewer/2022061614/56649d4d5503460f94a2c9a0/html5/thumbnails/7.jpg)
Chapter 4: Lists and the Collection Interface 7
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”);
![Page 8: Lists and the Collection Interface Chapter 4 Chapter 4: Lists and the Collection Interface2 Chapter Objectives To become familiar with the List interface.](https://reader033.fdocuments.us/reader033/viewer/2022061614/56649d4d5503460f94a2c9a0/html5/thumbnails/8.jpg)
Chapter 4: Lists and the Collection Interface 8
The ArrayList Class
• Then
• After myList.add(2, “Doc”);
• After myList.add(“Dopey”);
![Page 9: Lists and the Collection Interface Chapter 4 Chapter 4: Lists and the Collection Interface2 Chapter Objectives To become familiar with the List interface.](https://reader033.fdocuments.us/reader033/viewer/2022061614/56649d4d5503460f94a2c9a0/html5/thumbnails/9.jpg)
Chapter 4: Lists and the Collection Interface 9
The ArrayList Class (continued)
• Suppose we have
• Then myList.remove(1);
• And myList.set(2, “Sneezy”);
![Page 10: Lists and the Collection Interface Chapter 4 Chapter 4: Lists and the Collection Interface2 Chapter Objectives To become familiar with the List interface.](https://reader033.fdocuments.us/reader033/viewer/2022061614/56649d4d5503460f94a2c9a0/html5/thumbnails/10.jpg)
Chapter 4: Lists and the Collection Interface 10
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.
![Page 11: Lists and the Collection Interface Chapter 4 Chapter 4: Lists and the Collection Interface2 Chapter Objectives To become familiar with the List interface.](https://reader033.fdocuments.us/reader033/viewer/2022061614/56649d4d5503460f94a2c9a0/html5/thumbnails/11.jpg)
Chapter 4: Lists and the Collection Interface 11
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
![Page 12: Lists and the Collection Interface Chapter 4 Chapter 4: Lists and the Collection Interface2 Chapter Objectives To become familiar with the List interface.](https://reader033.fdocuments.us/reader033/viewer/2022061614/56649d4d5503460f94a2c9a0/html5/thumbnails/12.jpg)
Chapter 4: Lists and the Collection Interface 12
Creating a Generic Collection
![Page 13: Lists and the Collection Interface Chapter 4 Chapter 4: Lists and the Collection Interface2 Chapter Objectives To become familiar with the List interface.](https://reader033.fdocuments.us/reader033/viewer/2022061614/56649d4d5503460f94a2c9a0/html5/thumbnails/13.jpg)
Chapter 4: Lists and the Collection Interface 13
Non-generic Example
• For exampleArrayList yourList = new ArrayList();yourList.add(new Integer(35));// element 0 is IntegeryourList.add(“bunny”); // element 1 is StringyourList.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!
![Page 14: Lists and the Collection Interface Chapter 4 Chapter 4: Lists and the Collection Interface2 Chapter Objectives To become familiar with the List interface.](https://reader033.fdocuments.us/reader033/viewer/2022061614/56649d4d5503460f94a2c9a0/html5/thumbnails/14.jpg)
Chapter 4: Lists and the Collection Interface 14
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
![Page 15: Lists and the Collection Interface Chapter 4 Chapter 4: Lists and the Collection Interface2 Chapter Objectives To become familiar with the List interface.](https://reader033.fdocuments.us/reader033/viewer/2022061614/56649d4d5503460f94a2c9a0/html5/thumbnails/15.jpg)
Chapter 4: Lists and the Collection Interface 15
Specification of the ArrayList Class
![Page 16: Lists and the Collection Interface Chapter 4 Chapter 4: Lists and the Collection Interface2 Chapter Objectives To become familiar with the List interface.](https://reader033.fdocuments.us/reader033/viewer/2022061614/56649d4d5503460f94a2c9a0/html5/thumbnails/16.jpg)
Chapter 4: Lists and the Collection Interface 16
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!
![Page 17: Lists and the Collection Interface Chapter 4 Chapter 4: Lists and the Collection Interface2 Chapter Objectives To become familiar with the List interface.](https://reader033.fdocuments.us/reader033/viewer/2022061614/56649d4d5503460f94a2c9a0/html5/thumbnails/17.jpg)
Chapter 4: Lists and the Collection Interface 17
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
![Page 18: Lists and the Collection Interface Chapter 4 Chapter 4: Lists and the Collection Interface2 Chapter Objectives To become familiar with the List interface.](https://reader033.fdocuments.us/reader033/viewer/2022061614/56649d4d5503460f94a2c9a0/html5/thumbnails/18.jpg)
Chapter 4: Lists and the Collection Interface 18
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
![Page 19: Lists and the Collection Interface Chapter 4 Chapter 4: Lists and the Collection Interface2 Chapter Objectives To become familiar with the List interface.](https://reader033.fdocuments.us/reader033/viewer/2022061614/56649d4d5503460f94a2c9a0/html5/thumbnails/19.jpg)
Chapter 4: Lists and the Collection Interface 19
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;. . . . .
![Page 20: Lists and the Collection Interface Chapter 4 Chapter 4: Lists and the Collection Interface2 Chapter Objectives To become familiar with the List interface.](https://reader033.fdocuments.us/reader033/viewer/2022061614/56649d4d5503460f94a2c9a0/html5/thumbnails/20.jpg)
Chapter 4: Lists and the Collection Interface 20
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?
![Page 21: Lists and the Collection Interface Chapter 4 Chapter 4: Lists and the Collection Interface2 Chapter Objectives To become familiar with the List interface.](https://reader033.fdocuments.us/reader033/viewer/2022061614/56649d4d5503460f94a2c9a0/html5/thumbnails/21.jpg)
Chapter 4: Lists and the Collection Interface 21
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
![Page 22: Lists and the Collection Interface Chapter 4 Chapter 4: Lists and the Collection Interface2 Chapter Objectives To become familiar with the List interface.](https://reader033.fdocuments.us/reader033/viewer/2022061614/56649d4d5503460f94a2c9a0/html5/thumbnails/22.jpg)
Chapter 4: Lists and the Collection Interface 22
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…
![Page 23: Lists and the Collection Interface Chapter 4 Chapter 4: Lists and the Collection Interface2 Chapter Objectives To become familiar with the List interface.](https://reader033.fdocuments.us/reader033/viewer/2022061614/56649d4d5503460f94a2c9a0/html5/thumbnails/23.jpg)
Chapter 4: Lists and the Collection Interface 23
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;
![Page 24: Lists and the Collection Interface Chapter 4 Chapter 4: Lists and the Collection Interface2 Chapter Objectives To become familiar with the List interface.](https://reader033.fdocuments.us/reader033/viewer/2022061614/56649d4d5503460f94a2c9a0/html5/thumbnails/24.jpg)
Chapter 4: Lists and the Collection Interface 24
Add(int index, E anEntry) Method
• The algorithm…• Make room by shifting data elements “up”• Insert anEntry at position index
• The picture…
![Page 25: Lists and the Collection Interface Chapter 4 Chapter 4: Lists and the Collection Interface2 Chapter Objectives To become familiar with the List interface.](https://reader033.fdocuments.us/reader033/viewer/2022061614/56649d4d5503460f94a2c9a0/html5/thumbnails/25.jpg)
Chapter 4: Lists and the Collection Interface 25
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++;
}
![Page 26: Lists and the Collection Interface Chapter 4 Chapter 4: Lists and the Collection Interface2 Chapter Objectives To become familiar with the List interface.](https://reader033.fdocuments.us/reader033/viewer/2022061614/56649d4d5503460f94a2c9a0/html5/thumbnails/26.jpg)
Chapter 4: Lists and the Collection Interface 26
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;
}
![Page 27: Lists and the Collection Interface Chapter 4 Chapter 4: Lists and the Collection Interface2 Chapter Objectives To become familiar with the List interface.](https://reader033.fdocuments.us/reader033/viewer/2022061614/56649d4d5503460f94a2c9a0/html5/thumbnails/27.jpg)
Chapter 4: Lists and the Collection Interface 27
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];
}
![Page 28: Lists and the Collection Interface Chapter 4 Chapter 4: Lists and the Collection Interface2 Chapter Objectives To become familiar with the List interface.](https://reader033.fdocuments.us/reader033/viewer/2022061614/56649d4d5503460f94a2c9a0/html5/thumbnails/28.jpg)
Chapter 4: Lists and the Collection Interface 28
remove Method
• The algorithm…• Remove element• Shift “down” to fill in the gap
• The picture…
![Page 29: Lists and the Collection Interface Chapter 4 Chapter 4: Lists and the Collection Interface2 Chapter Objectives To become familiar with the List interface.](https://reader033.fdocuments.us/reader033/viewer/2022061614/56649d4d5503460f94a2c9a0/html5/thumbnails/29.jpg)
Chapter 4: Lists and the Collection Interface 29
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;
}
![Page 30: Lists and the Collection Interface Chapter 4 Chapter 4: Lists and the Collection Interface2 Chapter Objectives To become familiar with the List interface.](https://reader033.fdocuments.us/reader033/viewer/2022061614/56649d4d5503460f94a2c9a0/html5/thumbnails/30.jpg)
Chapter 4: Lists and the Collection Interface 30
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;
}
![Page 31: Lists and the Collection Interface Chapter 4 Chapter 4: Lists and the Collection Interface2 Chapter Objectives To become familiar with the List interface.](https://reader033.fdocuments.us/reader033/viewer/2022061614/56649d4d5503460f94a2c9a0/html5/thumbnails/31.jpg)
Chapter 4: Lists and the Collection Interface 31
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;
![Page 32: Lists and the Collection Interface Chapter 4 Chapter 4: Lists and the Collection Interface2 Chapter Objectives To become familiar with the List interface.](https://reader033.fdocuments.us/reader033/viewer/2022061614/56649d4d5503460f94a2c9a0/html5/thumbnails/32.jpg)
Chapter 4: Lists and the Collection Interface 32
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?
![Page 33: Lists and the Collection Interface Chapter 4 Chapter 4: Lists and the Collection Interface2 Chapter Objectives To become familiar with the List interface.](https://reader033.fdocuments.us/reader033/viewer/2022061614/56649d4d5503460f94a2c9a0/html5/thumbnails/33.jpg)
Chapter 4: Lists and the Collection Interface 33
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…)
![Page 34: Lists and the Collection Interface Chapter 4 Chapter 4: Lists and the Collection Interface2 Chapter Objectives To become familiar with the List interface.](https://reader033.fdocuments.us/reader033/viewer/2022061614/56649d4d5503460f94a2c9a0/html5/thumbnails/34.jpg)
Chapter 4: Lists and the Collection Interface 34
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?
![Page 35: Lists and the Collection Interface Chapter 4 Chapter 4: Lists and the Collection Interface2 Chapter Objectives To become familiar with the List interface.](https://reader033.fdocuments.us/reader033/viewer/2022061614/56649d4d5503460f94a2c9a0/html5/thumbnails/35.jpg)
Chapter 4: Lists and the Collection Interface 35
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?
![Page 36: Lists and the Collection Interface Chapter 4 Chapter 4: Lists and the Collection Interface2 Chapter Objectives To become familiar with the List interface.](https://reader033.fdocuments.us/reader033/viewer/2022061614/56649d4d5503460f94a2c9a0/html5/thumbnails/36.jpg)
Chapter 4: Lists and the Collection Interface 36
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
![Page 37: Lists and the Collection Interface Chapter 4 Chapter 4: Lists and the Collection Interface2 Chapter Objectives To become familiar with the List interface.](https://reader033.fdocuments.us/reader033/viewer/2022061614/56649d4d5503460f94a2c9a0/html5/thumbnails/37.jpg)
Chapter 4: Lists and the Collection Interface 37
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
![Page 38: Lists and the Collection Interface Chapter 4 Chapter 4: Lists and the Collection Interface2 Chapter Objectives To become familiar with the List interface.](https://reader033.fdocuments.us/reader033/viewer/2022061614/56649d4d5503460f94a2c9a0/html5/thumbnails/38.jpg)
Chapter 4: Lists and the Collection Interface 38
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!
![Page 39: Lists and the Collection Interface Chapter 4 Chapter 4: Lists and the Collection Interface2 Chapter Objectives To become familiar with the List interface.](https://reader033.fdocuments.us/reader033/viewer/2022061614/56649d4d5503460f94a2c9a0/html5/thumbnails/39.jpg)
Chapter 4: Lists and the Collection Interface 39
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
![Page 40: Lists and the Collection Interface Chapter 4 Chapter 4: Lists and the Collection Interface2 Chapter Objectives To become familiar with the List interface.](https://reader033.fdocuments.us/reader033/viewer/2022061614/56649d4d5503460f94a2c9a0/html5/thumbnails/40.jpg)
Chapter 4: Lists and the Collection Interface 40
Traversing a Linked List
• A fairly simple process:
1. Set nodeRef to reference of first node (head)
2. while nodeRef is not null3. do something with node referenced by nodeRef4. 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!
![Page 41: Lists and the Collection Interface Chapter 4 Chapter 4: Lists and the Collection Interface2 Chapter Objectives To become familiar with the List interface.](https://reader033.fdocuments.us/reader033/viewer/2022061614/56649d4d5503460f94a2c9a0/html5/thumbnails/41.jpg)
Chapter 4: Lists and the Collection Interface 41
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
![Page 42: Lists and the Collection Interface Chapter 4 Chapter 4: Lists and the Collection Interface2 Chapter Objectives To become familiar with the List interface.](https://reader033.fdocuments.us/reader033/viewer/2022061614/56649d4d5503460f94a2c9a0/html5/thumbnails/42.jpg)
Chapter 4: Lists and the Collection Interface 42
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
![Page 43: Lists and the Collection Interface Chapter 4 Chapter 4: Lists and the Collection Interface2 Chapter Objectives To become familiar with the List interface.](https://reader033.fdocuments.us/reader033/viewer/2022061614/56649d4d5503460f94a2c9a0/html5/thumbnails/43.jpg)
Chapter 4: Lists and the Collection Interface 43
Double-Linked List: Example
![Page 44: Lists and the Collection Interface Chapter 4 Chapter 4: Lists and the Collection Interface2 Chapter Objectives To become familiar with the List interface.](https://reader033.fdocuments.us/reader033/viewer/2022061614/56649d4d5503460f94a2c9a0/html5/thumbnails/44.jpg)
Chapter 4: Lists and the Collection Interface 44
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
![Page 45: Lists and the Collection Interface Chapter 4 Chapter 4: Lists and the Collection Interface2 Chapter Objectives To become familiar with the List interface.](https://reader033.fdocuments.us/reader033/viewer/2022061614/56649d4d5503460f94a2c9a0/html5/thumbnails/45.jpg)
Chapter 4: Lists and the Collection Interface 45
Double-Linked List: Insert
![Page 46: Lists and the Collection Interface Chapter 4 Chapter 4: Lists and the Collection Interface2 Chapter Objectives To become familiar with the List interface.](https://reader033.fdocuments.us/reader033/viewer/2022061614/56649d4d5503460f94a2c9a0/html5/thumbnails/46.jpg)
Chapter 4: Lists and the Collection Interface 46
Double-Linked List: Insert
![Page 47: Lists and the Collection Interface Chapter 4 Chapter 4: Lists and the Collection Interface2 Chapter Objectives To become familiar with the List interface.](https://reader033.fdocuments.us/reader033/viewer/2022061614/56649d4d5503460f94a2c9a0/html5/thumbnails/47.jpg)
Chapter 4: Lists and the Collection Interface 47
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
![Page 48: Lists and the Collection Interface Chapter 4 Chapter 4: Lists and the Collection Interface2 Chapter Objectives To become familiar with the List interface.](https://reader033.fdocuments.us/reader033/viewer/2022061614/56649d4d5503460f94a2c9a0/html5/thumbnails/48.jpg)
Chapter 4: Lists and the Collection Interface 48
Double-Linked List: Insert (Again)
![Page 49: Lists and the Collection Interface Chapter 4 Chapter 4: Lists and the Collection Interface2 Chapter Objectives To become familiar with the List interface.](https://reader033.fdocuments.us/reader033/viewer/2022061614/56649d4d5503460f94a2c9a0/html5/thumbnails/49.jpg)
Chapter 4: Lists and the Collection Interface 49
Double-Linked List: Insert (Again)
![Page 50: Lists and the Collection Interface Chapter 4 Chapter 4: Lists and the Collection Interface2 Chapter Objectives To become familiar with the List interface.](https://reader033.fdocuments.us/reader033/viewer/2022061614/56649d4d5503460f94a2c9a0/html5/thumbnails/50.jpg)
Chapter 4: Lists and the Collection Interface 50
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
![Page 51: Lists and the Collection Interface Chapter 4 Chapter 4: Lists and the Collection Interface2 Chapter Objectives To become familiar with the List interface.](https://reader033.fdocuments.us/reader033/viewer/2022061614/56649d4d5503460f94a2c9a0/html5/thumbnails/51.jpg)
Chapter 4: Lists and the Collection Interface 51
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
![Page 52: Lists and the Collection Interface Chapter 4 Chapter 4: Lists and the Collection Interface2 Chapter Objectives To become familiar with the List interface.](https://reader033.fdocuments.us/reader033/viewer/2022061614/56649d4d5503460f94a2c9a0/html5/thumbnails/52.jpg)
Chapter 4: Lists and the Collection Interface 52
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!
![Page 53: Lists and the Collection Interface Chapter 4 Chapter 4: Lists and the Collection Interface2 Chapter Objectives To become familiar with the List interface.](https://reader033.fdocuments.us/reader033/viewer/2022061614/56649d4d5503460f94a2c9a0/html5/thumbnails/53.jpg)
Chapter 4: Lists and the Collection Interface 53
Circular Double-Linked List
![Page 54: Lists and the Collection Interface Chapter 4 Chapter 4: Lists and the Collection Interface2 Chapter Objectives To become familiar with the List interface.](https://reader033.fdocuments.us/reader033/viewer/2022061614/56649d4d5503460f94a2c9a0/html5/thumbnails/54.jpg)
Chapter 4: Lists and the Collection Interface 54
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
![Page 55: Lists and the Collection Interface Chapter 4 Chapter 4: Lists and the Collection Interface2 Chapter Objectives To become familiar with the List interface.](https://reader033.fdocuments.us/reader033/viewer/2022061614/56649d4d5503460f94a2c9a0/html5/thumbnails/55.jpg)
Chapter 4: Lists and the Collection Interface 55
LinkedList<E> Class
![Page 56: Lists and the Collection Interface Chapter 4 Chapter 4: Lists and the Collection Interface2 Chapter Objectives To become familiar with the List interface.](https://reader033.fdocuments.us/reader033/viewer/2022061614/56649d4d5503460f94a2c9a0/html5/thumbnails/56.jpg)
Chapter 4: Lists and the Collection Interface 56
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?
![Page 57: Lists and the Collection Interface Chapter 4 Chapter 4: Lists and the Collection Interface2 Chapter Objectives To become familiar with the List interface.](https://reader033.fdocuments.us/reader033/viewer/2022061614/56649d4d5503460f94a2c9a0/html5/thumbnails/57.jpg)
Chapter 4: Lists and the Collection Interface 57
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
![Page 58: Lists and the Collection Interface Chapter 4 Chapter 4: Lists and the Collection Interface2 Chapter Objectives To become familiar with the List interface.](https://reader033.fdocuments.us/reader033/viewer/2022061614/56649d4d5503460f94a2c9a0/html5/thumbnails/58.jpg)
Chapter 4: Lists and the Collection Interface 58
Iterator<E> Interface
• Suppose iter declared an Iterator for myList• Where myList is a LinkedList
• Then can access each element usingwhile (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?
![Page 59: Lists and the Collection Interface Chapter 4 Chapter 4: Lists and the Collection Interface2 Chapter Objectives To become familiar with the List interface.](https://reader033.fdocuments.us/reader033/viewer/2022061614/56649d4d5503460f94a2c9a0/html5/thumbnails/59.jpg)
Chapter 4: Lists and the Collection Interface 59
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
![Page 60: Lists and the Collection Interface Chapter 4 Chapter 4: Lists and the Collection Interface2 Chapter Objectives To become familiar with the List interface.](https://reader033.fdocuments.us/reader033/viewer/2022061614/56649d4d5503460f94a2c9a0/html5/thumbnails/60.jpg)
Chapter 4: Lists and the Collection Interface 60
Iterator<E> Interface
![Page 61: Lists and the Collection Interface Chapter 4 Chapter 4: Lists and the Collection Interface2 Chapter Objectives To become familiar with the List interface.](https://reader033.fdocuments.us/reader033/viewer/2022061614/56649d4d5503460f94a2c9a0/html5/thumbnails/61.jpg)
Chapter 4: Lists and the Collection Interface 61
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();}
}
![Page 62: Lists and the Collection Interface Chapter 4 Chapter 4: Lists and the Collection Interface2 Chapter Objectives To become familiar with the List interface.](https://reader033.fdocuments.us/reader033/viewer/2022061614/56649d4d5503460f94a2c9a0/html5/thumbnails/62.jpg)
Chapter 4: Lists and the Collection Interface 62
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
![Page 63: Lists and the Collection Interface Chapter 4 Chapter 4: Lists and the Collection Interface2 Chapter Objectives To become familiar with the List interface.](https://reader033.fdocuments.us/reader033/viewer/2022061614/56649d4d5503460f94a2c9a0/html5/thumbnails/63.jpg)
Chapter 4: Lists and the Collection Interface 63
ListIterator<E> Interface
![Page 64: Lists and the Collection Interface Chapter 4 Chapter 4: Lists and the Collection Interface2 Chapter Objectives To become familiar with the List interface.](https://reader033.fdocuments.us/reader033/viewer/2022061614/56649d4d5503460f94a2c9a0/html5/thumbnails/64.jpg)
Chapter 4: Lists and the Collection Interface 64
ListIterator<E> Interface
• Create ListIterator starting between elements 2 and 3ListIterator<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()
![Page 65: Lists and the Collection Interface Chapter 4 Chapter 4: Lists and the Collection Interface2 Chapter Objectives To become familiar with the List interface.](https://reader033.fdocuments.us/reader033/viewer/2022061614/56649d4d5503460f94a2c9a0/html5/thumbnails/65.jpg)
Chapter 4: Lists and the Collection Interface 65
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?
![Page 66: Lists and the Collection Interface Chapter 4 Chapter 4: Lists and the Collection Interface2 Chapter Objectives To become familiar with the List interface.](https://reader033.fdocuments.us/reader033/viewer/2022061614/56649d4d5503460f94a2c9a0/html5/thumbnails/66.jpg)
Chapter 4: Lists and the Collection Interface 66
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
![Page 67: Lists and the Collection Interface Chapter 4 Chapter 4: Lists and the Collection Interface2 Chapter Objectives To become familiar with the List interface.](https://reader033.fdocuments.us/reader033/viewer/2022061614/56649d4d5503460f94a2c9a0/html5/thumbnails/67.jpg)
Chapter 4: Lists and the Collection Interface 67
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
![Page 68: Lists and the Collection Interface Chapter 4 Chapter 4: Lists and the Collection Interface2 Chapter Objectives To become familiar with the List interface.](https://reader033.fdocuments.us/reader033/viewer/2022061614/56649d4d5503460f94a2c9a0/html5/thumbnails/68.jpg)
Chapter 4: Lists and the Collection Interface 68
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
![Page 69: Lists and the Collection Interface Chapter 4 Chapter 4: Lists and the Collection Interface2 Chapter Objectives To become familiar with the List interface.](https://reader033.fdocuments.us/reader033/viewer/2022061614/56649d4d5503460f94a2c9a0/html5/thumbnails/69.jpg)
Chapter 4: Lists and the Collection Interface 69
The Enhanced for Statement
![Page 70: Lists and the Collection Interface Chapter 4 Chapter 4: Lists and the Collection Interface2 Chapter Objectives To become familiar with the List interface.](https://reader033.fdocuments.us/reader033/viewer/2022061614/56649d4d5503460f94a2c9a0/html5/thumbnails/70.jpg)
Chapter 4: Lists and the Collection Interface 70
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
![Page 71: Lists and the Collection Interface Chapter 4 Chapter 4: Lists and the Collection Interface2 Chapter Objectives To become familiar with the List interface.](https://reader033.fdocuments.us/reader033/viewer/2022061614/56649d4d5503460f94a2c9a0/html5/thumbnails/71.jpg)
Chapter 4: Lists and the Collection Interface 71
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…
![Page 72: Lists and the Collection Interface Chapter 4 Chapter 4: Lists and the Collection Interface2 Chapter Objectives To become familiar with the List interface.](https://reader033.fdocuments.us/reader033/viewer/2022061614/56649d4d5503460f94a2c9a0/html5/thumbnails/72.jpg)
Chapter 4: Lists and the Collection Interface 72
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;
![Page 73: Lists and the Collection Interface Chapter 4 Chapter 4: Lists and the Collection Interface2 Chapter Objectives To become familiar with the List interface.](https://reader033.fdocuments.us/reader033/viewer/2022061614/56649d4d5503460f94a2c9a0/html5/thumbnails/73.jpg)
Chapter 4: Lists and the Collection Interface 73
KWLinkedList Data Fields
![Page 74: Lists and the Collection Interface Chapter 4 Chapter 4: Lists and the Collection Interface2 Chapter Objectives To become familiar with the List interface.](https://reader033.fdocuments.us/reader033/viewer/2022061614/56649d4d5503460f94a2c9a0/html5/thumbnails/74.jpg)
Chapter 4: Lists and the Collection Interface 74
KWLinkedList Methods
• add(int index, E obj)• get(int index)• listIterator(int index)
![Page 75: Lists and the Collection Interface Chapter 4 Chapter 4: Lists and the Collection Interface2 Chapter Objectives To become familiar with the List interface.](https://reader033.fdocuments.us/reader033/viewer/2022061614/56649d4d5503460f94a2c9a0/html5/thumbnails/75.jpg)
Chapter 4: Lists and the Collection Interface 75
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
![Page 76: Lists and the Collection Interface Chapter 4 Chapter 4: Lists and the Collection Interface2 Chapter Objectives To become familiar with the List interface.](https://reader033.fdocuments.us/reader033/viewer/2022061614/56649d4d5503460f94a2c9a0/html5/thumbnails/76.jpg)
Chapter 4: Lists and the Collection Interface 76
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
![Page 77: Lists and the Collection Interface Chapter 4 Chapter 4: Lists and the Collection Interface2 Chapter Objectives To become familiar with the List interface.](https://reader033.fdocuments.us/reader033/viewer/2022061614/56649d4d5503460f94a2c9a0/html5/thumbnails/77.jpg)
Chapter 4: Lists and the Collection Interface 77
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
![Page 78: Lists and the Collection Interface Chapter 4 Chapter 4: Lists and the Collection Interface2 Chapter Objectives To become familiar with the List interface.](https://reader033.fdocuments.us/reader033/viewer/2022061614/56649d4d5503460f94a2c9a0/html5/thumbnails/78.jpg)
Chapter 4: Lists and the Collection Interface 78
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
![Page 79: Lists and the Collection Interface Chapter 4 Chapter 4: Lists and the Collection Interface2 Chapter Objectives To become familiar with the List interface.](https://reader033.fdocuments.us/reader033/viewer/2022061614/56649d4d5503460f94a2c9a0/html5/thumbnails/79.jpg)
Chapter 4: Lists and the Collection Interface 79
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;
![Page 80: Lists and the Collection Interface Chapter 4 Chapter 4: Lists and the Collection Interface2 Chapter Objectives To become familiar with the List interface.](https://reader033.fdocuments.us/reader033/viewer/2022061614/56649d4d5503460f94a2c9a0/html5/thumbnails/80.jpg)
Chapter 4: Lists and the Collection Interface 80
KWListIter Data Fields
![Page 81: Lists and the Collection Interface Chapter 4 Chapter 4: Lists and the Collection Interface2 Chapter Objectives To become familiar with the List interface.](https://reader033.fdocuments.us/reader033/viewer/2022061614/56649d4d5503460f94a2c9a0/html5/thumbnails/81.jpg)
Chapter 4: Lists and the Collection Interface 81
KWListIter Constructorpublic 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 beginningnextItem = head;for (index = 0; index < i; index++) {
nextItem = nextItem.next;}
}}
![Page 82: Lists and the Collection Interface Chapter 4 Chapter 4: Lists and the Collection Interface2 Chapter Objectives To become familiar with the List interface.](https://reader033.fdocuments.us/reader033/viewer/2022061614/56649d4d5503460f94a2c9a0/html5/thumbnails/82.jpg)
Chapter 4: Lists and the Collection Interface 82
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;}
![Page 83: Lists and the Collection Interface Chapter 4 Chapter 4: Lists and the Collection Interface2 Chapter Objectives To become familiar with the List interface.](https://reader033.fdocuments.us/reader033/viewer/2022061614/56649d4d5503460f94a2c9a0/html5/thumbnails/83.jpg)
Chapter 4: Lists and the Collection Interface 83
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;
}
![Page 84: Lists and the Collection Interface Chapter 4 Chapter 4: Lists and the Collection Interface2 Chapter Objectives To become familiar with the List interface.](https://reader033.fdocuments.us/reader033/viewer/2022061614/56649d4d5503460f94a2c9a0/html5/thumbnails/84.jpg)
Chapter 4: Lists and the Collection Interface 84
KWLinkedList and KWListIter Example
![Page 85: Lists and the Collection Interface Chapter 4 Chapter 4: Lists and the Collection Interface2 Chapter Objectives To become familiar with the List interface.](https://reader033.fdocuments.us/reader033/viewer/2022061614/56649d4d5503460f94a2c9a0/html5/thumbnails/85.jpg)
Chapter 4: Lists and the Collection Interface 85
Advancing KWListIter
![Page 86: Lists and the Collection Interface Chapter 4 Chapter 4: Lists and the Collection Interface2 Chapter Objectives To become familiar with the List interface.](https://reader033.fdocuments.us/reader033/viewer/2022061614/56649d4d5503460f94a2c9a0/html5/thumbnails/86.jpg)
Chapter 4: Lists and the Collection Interface 86
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;
}
![Page 87: Lists and the Collection Interface Chapter 4 Chapter 4: Lists and the Collection Interface2 Chapter Objectives To become familiar with the List interface.](https://reader033.fdocuments.us/reader033/viewer/2022061614/56649d4d5503460f94a2c9a0/html5/thumbnails/87.jpg)
Chapter 4: Lists and the Collection Interface 87
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;
}
![Page 88: Lists and the Collection Interface Chapter 4 Chapter 4: Lists and the Collection Interface2 Chapter Objectives To become familiar with the List interface.](https://reader033.fdocuments.us/reader033/viewer/2022061614/56649d4d5503460f94a2c9a0/html5/thumbnails/88.jpg)
Chapter 4: Lists and the Collection Interface 88
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
![Page 89: Lists and the Collection Interface Chapter 4 Chapter 4: Lists and the Collection Interface2 Chapter Objectives To become familiar with the List interface.](https://reader033.fdocuments.us/reader033/viewer/2022061614/56649d4d5503460f94a2c9a0/html5/thumbnails/89.jpg)
Chapter 4: Lists and the Collection Interface 89
add to Empty List
public void add(E obj) {if (head == null) { // Add to empty list.
head = new Node < E > (obj);tail = head;
}
![Page 90: Lists and the Collection Interface Chapter 4 Chapter 4: Lists and the Collection Interface2 Chapter Objectives To become familiar with the List interface.](https://reader033.fdocuments.us/reader033/viewer/2022061614/56649d4d5503460f94a2c9a0/html5/thumbnails/90.jpg)
Chapter 4: Lists and the Collection Interface 90
add to Empty List
![Page 91: Lists and the Collection Interface Chapter 4 Chapter 4: Lists and the Collection Interface2 Chapter Objectives To become familiar with the List interface.](https://reader033.fdocuments.us/reader033/viewer/2022061614/56649d4d5503460f94a2c9a0/html5/thumbnails/91.jpg)
Chapter 4: Lists and the Collection Interface 91
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
}
![Page 92: Lists and the Collection Interface Chapter 4 Chapter 4: Lists and the Collection Interface2 Chapter Objectives To become familiar with the List interface.](https://reader033.fdocuments.us/reader033/viewer/2022061614/56649d4d5503460f94a2c9a0/html5/thumbnails/92.jpg)
Chapter 4: Lists and the Collection Interface 92
add to Head of List
![Page 93: Lists and the Collection Interface Chapter 4 Chapter 4: Lists and the Collection Interface2 Chapter Objectives To become familiar with the List interface.](https://reader033.fdocuments.us/reader033/viewer/2022061614/56649d4d5503460f94a2c9a0/html5/thumbnails/93.jpg)
Chapter 4: Lists and the Collection Interface 93
add to Tail of List
else if (nextItem == null) {// Insert tail// Create a new nodeNode < 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
}
![Page 94: Lists and the Collection Interface Chapter 4 Chapter 4: Lists and the Collection Interface2 Chapter Objectives To become familiar with the List interface.](https://reader033.fdocuments.us/reader033/viewer/2022061614/56649d4d5503460f94a2c9a0/html5/thumbnails/94.jpg)
Chapter 4: Lists and the Collection Interface 94
add to Tail of List
![Page 95: Lists and the Collection Interface Chapter 4 Chapter 4: Lists and the Collection Interface2 Chapter Objectives To become familiar with the List interface.](https://reader033.fdocuments.us/reader033/viewer/2022061614/56649d4d5503460f94a2c9a0/html5/thumbnails/95.jpg)
Chapter 4: Lists and the Collection Interface 95
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 1nextItem.prev.next = newNode; // Step 2// Link it to the nextItem.newNode.next = nextItem; // Step 3nextItem.prev = newNode; // Step 4
}
![Page 96: Lists and the Collection Interface Chapter 4 Chapter 4: Lists and the Collection Interface2 Chapter Objectives To become familiar with the List interface.](https://reader033.fdocuments.us/reader033/viewer/2022061614/56649d4d5503460f94a2c9a0/html5/thumbnails/96.jpg)
Chapter 4: Lists and the Collection Interface 96
add to Middle of List
![Page 97: Lists and the Collection Interface Chapter 4 Chapter 4: Lists and the Collection Interface2 Chapter Objectives To become familiar with the List interface.](https://reader033.fdocuments.us/reader033/viewer/2022061614/56649d4d5503460f94a2c9a0/html5/thumbnails/97.jpg)
Chapter 4: Lists and the Collection Interface 97
add … The Last Word
// Increase size, index, set lastItemReturnedsize++;index++;lastItemReturned = null;
} // End of method add.
![Page 98: Lists and the Collection Interface Chapter 4 Chapter 4: Lists and the Collection Interface2 Chapter Objectives To become familiar with the List interface.](https://reader033.fdocuments.us/reader033/viewer/2022061614/56649d4d5503460f94a2c9a0/html5/thumbnails/98.jpg)
Chapter 4: Lists and the Collection Interface 98
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
![Page 99: Lists and the Collection Interface Chapter 4 Chapter 4: Lists and the Collection Interface2 Chapter Objectives To become familiar with the List interface.](https://reader033.fdocuments.us/reader033/viewer/2022061614/56649d4d5503460f94a2c9a0/html5/thumbnails/99.jpg)
Chapter 4: Lists and the Collection Interface 99
Application of the LinkedList Class
• Case study that uses the Java LinkedList class to solve a common problem: maintaining an ordered list
![Page 100: Lists and the Collection Interface Chapter 4 Chapter 4: Lists and the Collection Interface2 Chapter Objectives To become familiar with the List interface.](https://reader033.fdocuments.us/reader033/viewer/2022061614/56649d4d5503460f94a2c9a0/html5/thumbnails/100.jpg)
Chapter 4: Lists and the Collection Interface 100
Application of the LinkedList Class (continued)
![Page 101: Lists and the Collection Interface Chapter 4 Chapter 4: Lists and the Collection Interface2 Chapter Objectives To become familiar with the List interface.](https://reader033.fdocuments.us/reader033/viewer/2022061614/56649d4d5503460f94a2c9a0/html5/thumbnails/101.jpg)
Chapter 4: Lists and the Collection Interface 101
Application of the LinkedList Class (continued)
![Page 102: Lists and the Collection Interface Chapter 4 Chapter 4: Lists and the Collection Interface2 Chapter Objectives To become familiar with the List interface.](https://reader033.fdocuments.us/reader033/viewer/2022061614/56649d4d5503460f94a2c9a0/html5/thumbnails/102.jpg)
Chapter 4: Lists and the Collection Interface 102
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
![Page 103: Lists and the Collection Interface Chapter 4 Chapter 4: Lists and the Collection Interface2 Chapter Objectives To become familiar with the List interface.](https://reader033.fdocuments.us/reader033/viewer/2022061614/56649d4d5503460f94a2c9a0/html5/thumbnails/103.jpg)
Chapter 4: Lists and the Collection Interface 103
The Collection Hierarchy (continued)
![Page 104: Lists and the Collection Interface Chapter 4 Chapter 4: Lists and the Collection Interface2 Chapter Objectives To become familiar with the List interface.](https://reader033.fdocuments.us/reader033/viewer/2022061614/56649d4d5503460f94a2c9a0/html5/thumbnails/104.jpg)
Chapter 4: Lists and the Collection Interface 104
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
![Page 105: Lists and the Collection Interface Chapter 4 Chapter 4: Lists and the Collection Interface2 Chapter Objectives To become familiar with the List interface.](https://reader033.fdocuments.us/reader033/viewer/2022061614/56649d4d5503460f94a2c9a0/html5/thumbnails/105.jpg)
Chapter 4: Lists and the Collection Interface 105
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
![Page 106: Lists and the Collection Interface Chapter 4 Chapter 4: Lists and the Collection Interface2 Chapter Objectives To become familiar with the List interface.](https://reader033.fdocuments.us/reader033/viewer/2022061614/56649d4d5503460f94a2c9a0/html5/thumbnails/106.jpg)
Chapter 4: Lists and the Collection Interface 106
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