8 List ADTs List concepts List applications A

  • Slides: 41
Download presentation
8 List ADTs • List concepts. • List applications. • A list ADT: requirements,

8 List ADTs • List concepts. • List applications. • A list ADT: requirements, contract. • Iterators. • Implementations of lists: using arrays, linked lists. • Lists in the Java class library. © 2001, D. A. Watt and D. F. Brown 1

List concepts (1) • A list is a sequence of elements, whose order is

List concepts (1) • A list is a sequence of elements, whose order is significant. Elements can added and removed anywhere in the list. • The length of a list is the number of elements it contains. • An empty list has length zero. • The concatenation of lists l 1 and l 2 is a list containing all the elements of l 1 followed by all the elements of l 2. • Traversal of a list (or iterating over a list) means visiting each of the list’s elements in turn, in some desired order. 2

List concepts (2) • Notation for lists: «a, b, …, z» . The empty

List concepts (2) • Notation for lists: «a, b, …, z» . The empty list is « » . § List notation is used here, but not supported by Java. • Examples of lists: fibonacci = « 1, 1, 2, 3, 5, 8, 13, 21, 44, 65» birthdays = « 2001 -02 -23, 2001 -05 -05, 2001 -11 -05» tour = «GLA, LHR, CDG, GLA» hamlet 1 = «‘to’, ‘be’, ‘or’, ‘not’, ‘to’, ‘be’» hamlet 2 = «‘that’, ‘is’, ‘the’, ‘question’» • Concatenation of hamlet 1 and hamlet 2: «‘to’, ‘be’, ‘or’, ‘not’, ‘to’, ‘be’, ‘that’, ‘is’, ‘the’, ‘question’» 3

Lists vs linked lists • Do not confuse the list ADT with linked-list data

Lists vs linked lists • Do not confuse the list ADT with linked-list data structures. • A list ADT can be implemented using different data structures (arrays, linked lists). • Linked-list data structures can be used to implement many ADTs (e. g. , stacks, queues, lists, sets). 4

List applications • A sentence is a list of words. § The order of

List applications • A sentence is a list of words. § The order of words is significant. § The same word can occur more than once in a sentence. • An itinerary is a list of places visited on a tour. § The order of places is significant. § The same place can occur more than once in an itinerary. • A log is a list of event records (e. g. , equipment faults). § The event records are in time order. 5

Example 1: simple text editor (1) • Consider a simple text editor that supports

Example 1: simple text editor (1) • Consider a simple text editor that supports insertion and deletion of complete lines only. • The user can load text from a file, or save the text to a file. • The user can select any line of the text: § directly (e. g. , by a mouse-click) § by searching for the next line matching a given search string. • The user can delete the selected line. • The user can insert a new line, either before or after the selected line. 6

Example 1 (2) • We can represent the text being edited by: § a

Example 1 (2) • We can represent the text being edited by: § a list of lines, text § the number of the selected line, sel (where 0 sel < length of text, or sel = – 1 if text is empty) • We can implement the user commands straightforwardly in terms of list operations, e. g. : § Delete: remove line sel of text. § Insert before: add the new line as line sel of text, then increment sel. § Insert after: increment sel, then add the new line as line sel of text. § Save: traverse text, writing each line to the output file. 7

List ADT: requirements • Requirements: 1) It must be possible to make a list

List ADT: requirements • Requirements: 1) It must be possible to make a list empty. 2) It must be possible to test whether a list is empty. 3) It must be possible to obtain the length of a list. 4) It must be possible to add an element anywhere in a list. 5) It must be possible to remove an element anywhere in a list. 6) It must be possible to inspect or update an element anywhere in a list. 7) It must be possible to concatenate lists. 8) It must be possible to test lists for equality. 9) It must be possible to traverse a list. 8

List ADT: contract (1) • Possible contract: public interface List { // Each List

List ADT: contract (1) • Possible contract: public interface List { // Each List object is an indexed list whose elements are // objects. ////// Accessors ////// public boolean is. Empty (); // Return true if and only if this list is empty. public int size (); // Return this list’s length. 9

List ADT: contract (2) • Possible contract (continued): public Object get (int i); //

List ADT: contract (2) • Possible contract (continued): public Object get (int i); // Return the element with index i in this list. public boolean equals (List that); // Return true if and only if this list and that have the same // length, and each element of this list equals the corresponding // element of that. 10

List ADT: contract (3) • Possible contract (continued): ////// Transformers ////// public void clear

List ADT: contract (3) • Possible contract (continued): ////// Transformers ////// public void clear (); // Make this list empty. public void set (int i, Object elem); // Replace by elem the element at index i in this list. public void add (int i, Object elem); // Add elem as the element with index i in this list. public void add (Object elem); // Add elem after the last element of this list. 11

List ADT: contract (4) • Possible contract (continued): public void add. All (List that);

List ADT: contract (4) • Possible contract (continued): public void add. All (List that); // Add all the elements of that after the last element of this list. public Object remove (int i); // Remove and return the element with index i in this list. ////// Iterator ////// public Iterator iterator (); // Return an iterator that will visit all elements of this list, in // left-to-right order. } 12

List traversal (1) • To traverse array a: for (int i = 0; i

List traversal (1) • To traverse array a: for (int i = 0; i < a. length; i++) … a[i] … • We could mimic this to traverse list: for (int i = 0; i < list. size(); i++) … list. get(i) … … list. set(i, x) … But this traversal has time complexity O(n 2), if get and set are O(n). 13

List traversal (2) • Better, use an iterator to traverse list: Iterator elems =

List traversal (2) • Better, use an iterator to traverse list: Iterator elems = list. iterator(); while (elems. has. Next()) { Object elem = elems. next(); … elem … } accesses the next element in that iterator constructs an iterator over the elements of list tests whether that iterator has any more elements This traversal has time complexity O(n). 14

Iterators (1) • Visualize an iterator as a chain to which elements are attached

Iterators (1) • Visualize an iterator as a chain to which elements are attached in the required order. • Examples of iterators over the list «‘to’, ‘be’, ‘or’, ‘not’, ‘to’, ‘be’» : left-to-right iterator « ‘to’ ‘be’ ‘or’ ‘not’ ‘to’ ‘be’ » right-to-left iterator « ‘to’ ‘be’ ‘or’ ‘not’ ‘to’ ‘be’ » left-to-right alternating iterator 15

Iterators (2) • The List interface’s iterator() operation constructs an iterator on which the

Iterators (2) • The List interface’s iterator() operation constructs an iterator on which the list elements are ‘chained’ from left to right. • The iterator’s next() operation returns the next element on the ‘chain’. • The iterator’s has. Next() operation tests whethere is a next element on the ‘chain’. 16

Iterators: contract • Java contract for iterators: public interface Iterator { // Each Iterator

Iterators: contract • Java contract for iterators: public interface Iterator { // Each Iterator object represents an iterator over some // collection. public boolean has. Next (); // Return true if and only if this iterator has a next element. public Object next (); // Return the next element in this iterator. … omitted operation } 17

Implementation of lists using arrays (1) • Represent a bounded list (length maxlen) by:

Implementation of lists using arrays (1) • Represent a bounded list (length maxlen) by: § a variable length, containing the current length § an array elems of length maxlen, containing the listed elements in elems[0… length– 1]: first element Invariant: Empty list: Illustration (maxlen = 6): last element 0 1 element length=0 1 0 GLA 1 LHR unoccupied length– 1 length element maxlen– 1 2 CDG 3 length=4 GLA 5 18

Implementation using arrays (2) • Java implementation: public class Array. List implements List {

Implementation using arrays (2) • Java implementation: public class Array. List implements List { private Object[] elems; private int length; ////// Constructor ////// public Array. List (int maxlen) { elems = new Object[maxlen]; length = 0; } 19

Implementation using arrays (3) • Java implementation (continued): ////// Accessors ////// public int size

Implementation using arrays (3) • Java implementation (continued): ////// Accessors ////// public int size () { return length; } public Object get (int i) { if (i < 0 || i >= length) return elems[i]; } throw …; … 20

Implementation using arrays (4) • Java implementation (continued): ////// Transformers ////// public void add

Implementation using arrays (4) • Java implementation (continued): ////// Transformers ////// public void add (int i, Object elem) { if (i < 0 || i > length) throw …; if (length == elems. length) …; for (int j = length; j > i; j--) elems[j] = elems[j-1]; elems[i] = elem; length++; } … 21

Implementation using arrays (5) • Java implementation (continued): ////// Iterator ////// public Iterator iterator

Implementation using arrays (5) • Java implementation (continued): ////// Iterator ////// public Iterator iterator () { return new LRIterator(); } ////// Inner class ////// private class LRIterator implements Iterator { … } } 22

Implementation using arrays (6) • Implementing iterators over Array. List objects: private class LRIterator

Implementation using arrays (6) • Implementing iterators over Array. List objects: private class LRIterator implements Iterator { // An LRIterator object is a left-to-right iterator over an // Array. List object. private int place; private LRIterator () { place = 0; } 23

Implementation using arrays (7) • Implementing iterators (continued): public boolean has. Next () {

Implementation using arrays (7) • Implementing iterators (continued): public boolean has. Next () { return (place < length); } public Object next () { if (place >= length) throw …; return elems[place++]; }. . . } 24

Implementation using arrays (8) • Since LRIterator is an inner class of Array. List,

Implementation using arrays (8) • Since LRIterator is an inner class of Array. List, its instance methods can access Array. List instance variables. E. g. : tour class tag elems length Array. List 4 class tag length Object[] 6 iter class tag LRIterator 0 GLA place 0 1 LHR 2 CDG 3 GLA 4 5 Iterator constructed by: iter = tour. iterator(); 25

Implementation of lists using SLLs (1) • Represent an (unbounded) list by: § a

Implementation of lists using SLLs (1) • Represent an (unbounded) list by: § a variable length § an SLL, with links first and last to both ends: first element Invariant: element last element Empty list: Illustration: GLA LHR CDG GLA 26

Implementation using SLLs (2) • Java implementation: public class Linked. List implements List {

Implementation using SLLs (2) • Java implementation: public class Linked. List implements List { private SLLNode first, last; private int length; ////// Constructor ////// public Linked. List () { first = last = null; length = 0; } 27

Implementation using SLLs (3) • Java implementation (continued): ////// Auxiliary method ////// private SLLNode

Implementation using SLLs (3) • Java implementation (continued): ////// Auxiliary method ////// private SLLNode node (int i) { // Return a link to the node containing the element with index i // in this list. SLLNode curr = first; for (int j = 0; j < i; j++) curr = curr. succ; return curr; } 28

Implementation using SLLs (4) • Java implementation (continued): ////// Accessors ////// public int size

Implementation using SLLs (4) • Java implementation (continued): ////// Accessors ////// public int size () { return length; } public Object get (int i) { if (i < 0 || i >= length) return node(i). element; } throw …; … 29

Implementation using SLLs (5) • Java implementation (continued): ////// Transformers ////// public void add

Implementation using SLLs (5) • Java implementation (continued): ////// Transformers ////// public void add (int i, Object elem) { if (i < 0 || i > length) throw …; SLLNode newest = new SLLNode(elem, null); if (i == 0) { newest. succ = first; first = newest; } else { SLLNode pred = node(i-1); newest. succ = pred. succ; pred. succ = newest; } if (newest. succ == null) last = 30

Implementation using SLLs (6) • Java implementation (continued): ////// Iterator ////// public Iterator iterator

Implementation using SLLs (6) • Java implementation (continued): ////// Iterator ////// public Iterator iterator () { return new LRIterator(); } ////// Inner class ////// private class LRIterator implements Iterator { … } } 31

Implementation using SLLs (7) • Implementing iterators over Linked. List objects: private class LRIterator

Implementation using SLLs (7) • Implementing iterators over Linked. List objects: private class LRIterator implements Iterator { // An LRIterator object is a left-to-right iterator over a // Linked. List object. private SLLNode place; private LRIterator () { place = first; } 32

Implementation using SLLs (8) • Implementing iterators (continued): public boolean has. Next () {

Implementation using SLLs (8) • Implementing iterators (continued): public boolean has. Next () { return (place != null); } public Object next () { if (place == null) throw …; Object next. Elem = place. element; place = place. succ; return next. Elem; }. . . } 33

Implementation using SLLs (9) • Since LRIterator is an inner class of Linked. List,

Implementation using SLLs (9) • Since LRIterator is an inner class of Linked. List, its instance methods can access Linked. List instance variables: tour class tag Linked. List first last length 4 class tag element succ SLLNode GLA iter class tag LRIterator place class tag element succ SLLNode GLA Iterator constructed by: iter = tour. iterator(); 34

Summary of list implementations • Time complexities of main operations: Operation Array representation SLL

Summary of list implementations • Time complexities of main operations: Operation Array representation SLL representation get O(1) O(n) set O(1) O(n) add(int, Object) O(n) add(Object) O(1) remove O(n) equals O(n 2) add. All O(n 2) 35

Lists in the Java class library • Java provides the interface java. util. List,

Lists in the Java class library • Java provides the interface java. util. List, similar to the List interface above. • Java provides the class java. util. Array. List, which implements the java. util. List interface, representing each list by an array. • Java provides the class java. util. Linked. List, which implements the java. util. List interface, representing each list by a DLL. 36

Example 2: simple text editor revisited (1) • Recall the simple text editor of

Example 2: simple text editor revisited (1) • Recall the simple text editor of Example 1. • Outline implementation: public class Text. Editor { private List text; private int sel; public Text. Editor () { text = new Array. List(); sel = -1; or: } new Linked. List() 37

Example 2 (2) • Outline implementation (continued): public void select (int ln) { if

Example 2 (2) • Outline implementation (continued): public void select (int ln) { if (ln < 0 || ln >= text. size()) throw …; sel = ln; } public void find (String s) { if (sel < 0) throw …; for (int ln = sel; ln < text. size(); ln++) { String line = text. get(ln); if (line. index. Of(s) >= 0) { // found s sel = ln; return; 38 }

Example 2 (3) • Outline implementation (continued): public void insert. Before (String line) {

Example 2 (3) • Outline implementation (continued): public void insert. Before (String line) { if (sel < 0) throw …; text. add(sel++, line); } public void insert. After (String line) { text. add(++sel, line); } public void delete () { if (sel < 0) throw …; text. remove(sel); if (sel == text. size()) } sel--; 39

Example 2 (4) • Outline implementation (continued): public void load (Buffered. Reader input) {

Example 2 (4) • Outline implementation (continued): public void load (Buffered. Reader input) { for (; ; ) { String line = input. read. Line(); if (line == null) break; text. add(line); } sel = text. size() - 1; } 40

Example 2 (5) • Outline implementation (continued): public void save (Buffered. Writer output) {

Example 2 (5) • Outline implementation (continued): public void save (Buffered. Writer output) { Iterator lines = text. iterator(); while (lines. has. Next()) { String line = (String) lines. next(); output. write(line + "n"); } } } 41