Lists and the Collection Interface Chapter 4 Chapter 4: Lists and the Collection Interface2 Chapter Objectives To become familiar with the List interface.

Slides:



Advertisements
Similar presentations
Chapter 23 Organizing list implementations. This chapter discusses n The notion of an iterator. n The standard Java library interface Collection, and.
Advertisements

Chapter 24 Lists, Stacks, and Queues
Lists and the Collection Interface Chapter 4. Chapter Objectives To become familiar with the List interface To understand how to write an array-based.
ITEC200 Week04 Lists and the Collection Interface.
COMP 121 Week 9: AbstractList and ArrayList. Objectives List common operations and properties of Lists as distinct from Collections Extend the AbstractCollection.
Double-Linked Lists and Circular Lists
Section 2.5 Single-Linked Lists. A linked list is useful for inserting and removing at arbitrary locations The ArrayList is limited because its add and.
The List ADT Textbook Sections
Chapter 6 The Collections API. Simple Container/ Iterator Simple Container Shape [] v = new Shape[10]; Simple Iterator For( int i=0 ; i< v.length ; i++)
CHAPTER 4 Queues. Queue  The queue, like the stack, is a widely used data structure  A queue differs from a stack in one important way  A stack is.
CHAPTER 4 Queues MIDTERM THURSDAY, OCTOBER 17 IN LAB.
COMP 121 Week 11: Linked Lists. Objectives Understand how single-, double-, and circular-linked list data structures are implemented Understand the LinkedList.
Lecture 8 CS203. Implementation of Data Structures 2 In the last couple of weeks, we have covered various data structures that are implemented in the.
Lists and the Collections Framework
1 Chapter 24 Lists Stacks and Queues. 2 Objectives F To design list with interface and abstract class (§24.2). F To design and implement a dynamic list.
Lists and the Collection Interface Chapter 4. Chapter 4: Lists and the Collection Interface2 Chapter Objectives To become familiar with the List interface.
Fall 2007CS 2251 Lists and the Collection Interface Chapter 4.
Sprint 2010CS 2251 Lists and the Collection Interface Chapter 2.
Unit 291 Java Collections Framework: Interfaces Introduction to the Java Collections Framework (JCF) The Comparator Interface Revisited The Collection.
1 Collections Working with More than One Number or Data Type or Object.
Cmp Sci 187: Midterm Review Based on Lecture Notes.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 26 Implementing Lists, Stacks,
List Interface CS java.util.List Interface and its Implementers CS340 2.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Implementing Stacks Ellen Walker CPSC 201 Data Structures Hiram College.
CHAPTER 2 Lists and the Collections Framework. Chapter Objectives  The List interface  Writing an array-based implementation of List  Linked list data.
Lists Ellen Walker CPSC 201 Data Structures Hiram College.
Lists and the Collection Interface Review inheritance & collections.
GENERICS. Generics  Classes and methods can have a type parameter (actually, more than one).  The type parameter can be any reference (class) type.
LinkedList Many slides from Horstmann modified by Dr V.
1 Chapter 17 Object-Oriented Data Structures. 2 Objectives F To describe what a data structure is (§17.1). F To explain the limitations of arrays (§17.1).
1/20/03A2-1 CS494 Interfaces and Collection in Java.
Linked Lists Ellen Walker CPSC 201 Data Structures Hiram College.
Lists and the Collection Interface Chapter 4. 2 The List Interface and ArrayList Class So far, all we have is an array for storing a collection of elements.
CIS3023: Programming Fundamentals for CIS Majors II Summer 2010 Ganesh Viswanathan Generics and Collections Course Lecture Slides 19 th July 2010 “Never.
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures for Java William H. Ford William R. Topp Chapter 13 Implementing.
Chapter 5 Array-Based Structures © 2006 Pearson Education Inc., Upper Saddle River, NJ. All rights reserved.
COMP 121 Week 11: Linked Lists.
Lecture Objectives  Linked list data structures:  Singly-linked (cont.)  Doubly-linked  Circular  Implementing the List interface as a linked list.
1 CMPSCI 187 Computer Science 187 Introduction to Introduction to Programming with Data Structures Lecture 8 Lists, Iterators, and Doubly Linked Lists.
© 2006 Pearson Addison-Wesley. All rights reserved5 B-1 Chapter 5 (continued) Linked Lists.
Copyright © 0 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java From Control Structures through Data Structures by Tony.
Chapter Objectives  The List interface  Implement lists based on arrays  Learn about List applications CS340 1.
Chapter 15 An Introduction to Data Structures. Chapter Goals To learn how to use the linked lists provided in the standard library To be able to use iterators.
List Interface and Linked List Mrs. Furman March 25, 2010.
Chapter 5 Array-Based Structures © 2006 Pearson Education Inc., Upper Saddle River, NJ. All rights reserved.
Chapter 5 Linked List by Before you learn Linked List 3 rd level of Data Structures Intermediate Level of Understanding for C++ Please.
Arrays and ArrayLists Topic 6. One Dimensional Arrays Homogeneous – all of the same type Contiguous – all elements are stored sequentially in memory For.
JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN © 2012 Pearson Education, Inc., Upper Saddle River,
Data Structures I Collection, List, ArrayList, LinkedList, Iterator, ListNode.
1 CMPSCI 187 Computer Science 187 Introduction to Introduction to Programming with Data Structures Lecture 9 Doubly Linked Lists and Ordered Lists Lecture.
CHAPTER 2 Lists and the Collections Framework. Chapter Objectives  The List interface  Writing an array-based implementation of List  Linked list data.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java From Control Structures through Data Structures by.
Lists and the Collection Interface Chapter 4. Chapter 4: Lists and the Collection Interface2 Chapter Objectives To become familiar with the List interface.
1 Chapter 24 Implementing Lists, Stacks, Queues, and Priority Queues Jung Soo (Sue) Lim Cal State LA.
Single-Linked Lists.
Lists and the Collections Framework
Linked Lists Chapter 5 (continued)
Fundamentals of Java: AP Computer Science Essentials, 4th Edition
COMP 121 Week 9: ArrayList.
Lists and the Collections Framework
Programming II (CS300) Chapter 07: Linked Lists and Iterators
Dynamic Data Structures and Generics
Chapter 24 Implementing Lists, Stacks, Queues, and Priority Queues
Lists and the Collection Interface
Single-Linked Lists Section 2.5.
ArrayLists 22-Feb-19.
Chapter 4 Queues.
Linked Lists Chapter 5 (continued)
Linked Lists Chapter 5 (continued)
Presentation transcript:

Lists and the Collection Interface Chapter 4

Chapter 4: Lists and the Collection Interface2 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 Interface3 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 Interface4 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 Interface5 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 Interface6 The List Interface and ArrayList Class (continued)

Chapter 4: Lists and the Collection Interface7 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 myList = new ArrayList (); myList.add(“Bashful”); myList.add(“Awful”); myList.add(“Jumpy”); myList.add(“Happy”);

Chapter 4: Lists and the Collection Interface8 The ArrayList Class Then After myList.add(2, “Doc”); After myList.add(“Dopey”);

Chapter 4: Lists and the Collection Interface9 The ArrayList Class (continued) Suppose we have Then myList.remove(1); And myList.set(2, “Sneezy”);

Chapter 4: Lists and the Collection Interface10 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 myList = new ArrayList (); 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 Interface11 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 Interface12 Creating a Generic Collection

Chapter 4: Lists and the Collection Interface13 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 Interface14 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 Interface15 Specification of the ArrayList Class

Chapter 4: Lists and the Collection Interface16 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 Interface17 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 Interface18 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 Interface19 KWArrayList Class Definition public class KWArrayList { // 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 Interface20 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 Interface21 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 Interface22 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 Interface23 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 Interface24 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 Interface25 Add(int index, E anEntry) Method The code… public void add(int index, E anEntry) { if (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 Interface26 set Method The algorithm and picture are fairly obvious… The code… public E set(int index, E newValue) { if (index = size) { throw new ArrayIndexOutOfBoundsException(index); } E oldValue = theData[index]; theData[index] = newValue; return oldValue; }

Chapter 4: Lists and the Collection Interface27 get Method The algorithm and picture are even more obvious… The code… public E get(int index) { if (index = size) { throw new ArrayIndexOutOfBoundsException(index); } return theData[index]; }

Chapter 4: Lists and the Collection Interface28 remove Method The algorithm… Remove element Shift “down” to fill in the gap The picture…

Chapter 4: Lists and the Collection Interface29 remove Method The code… public E remove(int index) { if (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 Interface30 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 Interface31 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 Interface32 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 Interface33 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 Interface34 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 Interface35 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 Interface36 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 Interface37 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 Interface38 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 Interface39 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 Interface40 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 Interface41 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 Interface42 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 Interface43 Double-Linked List: Example

Chapter 4: Lists and the Collection Interface44 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 Interface45 Double-Linked List: Insert

Chapter 4: Lists and the Collection Interface46 Double-Linked List: Insert

Chapter 4: Lists and the Collection Interface47 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 Interface48 Double-Linked List: Insert (Again)

Chapter 4: Lists and the Collection Interface49 Double-Linked List: Insert (Again)

Chapter 4: Lists and the Collection Interface50 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 Interface51 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 Interface52 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 Interface53 Circular Double-Linked List

Chapter 4: Lists and the Collection Interface54 LinkedList Class Part of Java API Package java.util Implements the List 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 Interface55 LinkedList Class

Chapter 4: Lists and the Collection Interface56 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(n 2 ) Can we do this more efficiently?

Chapter 4: Lists and the Collection Interface57 Iterator 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 Interface58 Iterator 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 Interface59 Iterator Interface Here, we process elements of List aList using the Iterator object itr Iterator 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 Interface60 Iterator Interface

Chapter 4: Lists and the Collection Interface61 Iterator 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 aList, int div) { Iterator iter = aList.iterator(); while (iter.hasNext()) { int nextInt = iter.next(); if (nextInt % div == 0) iter.remove(); }

Chapter 4: Lists and the Collection Interface62 ListIterator 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 extends Iterator interface And it overcomes above limitations As with Iterator, a ListIterator lives “between” elements of the linked list

Chapter 4: Lists and the Collection Interface63 ListIterator Interface

Chapter 4: Lists and the Collection Interface64 ListIterator Interface Create ListIterator starting between elements 2 and 3 List Iterator 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 Interface65 ListIterator Interface To search for first occurrence of target and replace with newItem could use the following… ListIterator 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 Interface66 Comparison of Iterator and ListIterator ListIterator is a subinterface of Iterator 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 Interface67 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 Interface68 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 Interface69 The Enhanced for Statement

Chapter 4: Lists and the Collection Interface70 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 Interface71 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 Interface72 KWLinkedList Data Fields import java.util.*; /** KWLinkedList implements a double-linked list */ public class KWLinkedList { // Data Fields /** A reference to the head of the list. */ private Node head = null; /** A reference to the end of the list. */ private Node tail = null; /** The size of the list. */ private int size = 0;

Chapter 4: Lists and the Collection Interface73 KWLinkedList Data Fields

Chapter 4: Lists and the Collection Interface74 KWLinkedList Methods add(int index, E obj) get(int index) listIterator(int index)

Chapter 4: Lists and the Collection Interface75 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 Interface76 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 Interface77 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 Interface78 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 Interface79 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 { /** A reference to the next item. */ private Node nextItem; /** A reference to the last item returned. */ private Node lastItemReturned; /** The index of the current item. */ private int index = 0;

Chapter 4: Lists and the Collection Interface80 KWListIter Data Fields

Chapter 4: Lists and the Collection Interface81 KWListIter Constructor public KWListIter(int i) { // Validate i parameter. if (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 Interface82 KWListIter hasNext Method /** Indicate whether movement forward is true if call to next will not throw an exception */ public boolean hasNext() { return nextItem != null; }

Chapter 4: Lists and the Collection Interface83 KWListIter next Method /** Move the iterator forward and return the next The next item in the 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 Interface84 KWLinkedList and KWListIter Example

Chapter 4: Lists and the Collection Interface85 Advancing KWListIter

Chapter 4: Lists and the Collection Interface86 KWListIter hasPrevious Method /** Indicate whether movement backward is 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 Interface87 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 Interface88 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 Interface89 add to Empty List public void add(E obj) { if (head == null) { // Add to empty list. head = new Node (obj); tail = head; }

Chapter 4: Lists and the Collection Interface90 add to Empty List

Chapter 4: Lists and the Collection Interface91 add to Head of List else if (nextItem == head) { // Insert at head // Create a new node. Node newNode = new Node (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 Interface92 add to Head of List

Chapter 4: Lists and the Collection Interface93 add to Tail of List else if (nextItem == null) {// Insert tail // Create a new node Node newNode = new Node (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 Interface94 add to Tail of List

Chapter 4: Lists and the Collection Interface95 add to Middle of List else { // Insert into the middle. // Create a new node. Node newNode = new Node (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 Interface96 add to Middle of List

Chapter 4: Lists and the Collection Interface97 add … The Last Word // Increase size, index, set lastItemReturned size++; index++; lastItemReturned = null; } // End of method add.

Chapter 4: Lists and the Collection Interface98 Inner Classes Two inner classes in KWLinkedList That is, Node and KWListIter Declare Node to be static No need for its methods to access data fields of parent class Cannot declare KWListIter to be static Its methods access and modify fields of KWLinkedList Type parameter is considered previously defined So, cannot appear as part of class name

Chapter 4: Lists and the Collection Interface99 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 Interface100 Application of the LinkedList Class (continued)

Chapter 4: Lists and the Collection Interface101 Application of the LinkedList Class (continued)

Chapter 4: Lists and the Collection Interface102 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 Interface103 The Collection Hierarchy (continued)

Chapter 4: Lists and the Collection Interface104 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 Interface105 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 Interface106 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