29
The List Interface The List Interface Cmput 115 - Lecture 14 Cmput 115 - Lecture 14 Department of Computing Department of Computing Science Science University of Alberta University of Alberta ©Duane Szafron 2000 ©Duane Szafron 2000 Some code in this lecture is based on code from the book: Java Structures by Duane A. Bailey or the companion structure package Revised 2/1/00

The List Interface Cmput 115 - Lecture 14 Department of Computing Science University of Alberta ©Duane Szafron 2000 Some code in this lecture is based

  • View
    212

  • Download
    0

Embed Size (px)

Citation preview

The List InterfaceThe List Interface

Cmput 115 - Lecture 14Cmput 115 - Lecture 14

Department of Computing ScienceDepartment of Computing Science

University of AlbertaUniversity of Alberta©Duane Szafron 2000©Duane Szafron 2000

Some code in this lecture is based on code from the book:Java Structures by Duane A. Bailey or the companion structure package

Revised 2/1/00

©Duane Szafron 2000 2

About This LectureAbout This Lecture

In this lecture we will learn about an In this lecture we will learn about an Interface called Interface called ListList and write an and write an example program that uses one of its example program that uses one of its implementations.implementations.

©Duane Szafron 2000 3

OutlineOutline

ListsLists

Structure Interface HierarchyStructure Interface Hierarchy for List for List

UtilUtil Interface HierarchyInterface Hierarchy for List for List

The The Store, CollectionStore, Collection and and ListList Interfaces Interfaces

Example of Using Lists - The Free ListExample of Using Lists - The Free List

©Duane Szafron 2000 4

A ListA List

A A List List is a non-indexed collection object is a non-indexed collection object that can grow and shrink at either end.that can grow and shrink at either end.

"Fred" "Barney" "Wilma"

"Fred" "Barney" "Wilma"”Pebbles" ”Betty"

"Fred" "Barney" "Wilma" ”Betty"

”Pebbles" ”Fred" ”Barney" ”Wilma"

©Duane Szafron 2000 5

Structure Collection HierarchyStructure Collection Hierarchy

In the In the structure packagestructure package and in and in java.utiljava.util, Vectors and , Vectors and Arrays are Arrays are containerscontainers, but they are , but they are not called collectionsnot called collections..

The The structure packagestructure package defines the following interface defines the following interface hierarchy.hierarchy.

Store

Collection

List

©Duane Szafron 2000 6

Util Collection HierarchyUtil Collection Hierarchy

In the In the java.util packagejava.util package, there is no , there is no StoreStore interfaceinterface.. In addition, the interfaces In addition, the interfaces CollectionCollection and and ListList have more have more

messages defined than in the messages defined than in the structure packagestructure package.. The The java.util packagejava.util package defines the following interface hierarchy. defines the following interface hierarchy.

Collection

List

©Duane Szafron 2000 7

Structure Interface - StoreStructure Interface - Store

public interface Storepublic interface Store{{

public int size();public int size();//post: returns the number of elements contained in //post: returns the number of elements contained in // the store.// the store.

public boolean isEmpty();public boolean isEmpty();// post: returns the true iff store is empty.// post: returns the true iff store is empty.

public void clear();public void clear();// post: clears the store so that it contains no // post: clears the store so that it contains no // elements// elements..

}}

code based on Bailey pg. 18

©Duane Szafron 2000 8

Structure Interface - CollectionStructure Interface - Collection

public interface Collection extends Storepublic interface Collection extends Store{ public boolean contains(Object anObject);{ public boolean contains(Object anObject);

// pre: anObject is non-null// pre: anObject is non-null// post: returns true iff the collection contains the object// post: returns true iff the collection contains the object

public void add(Object anObject);public void add(Object anObject);// pre: anObject is non-null// pre: anObject is non-null// post: the object is added to the collection. The // post: the object is added to the collection. The // replacement policy is not specified// replacement policy is not specified

public void remove(Object anObject);public void remove(Object anObject);// pre: anObject is non-null// pre: anObject is non-null// post: removes an object “equal” to anObject// post: removes an object “equal” to anObject

public iterator elements();public iterator elements();// post: return an iterator for traversing the collection// post: return an iterator for traversing the collection

}}code based on Bailey pg. 19

©Duane Szafron 2000 9

Structure Interface - List 1Structure Interface - List 1

public interfacepublic interface ListList extendsextends CollectionCollection{{

public void addToHead(Object anObject);public void addToHead(Object anObject);// pre: anObject is non-null// pre: anObject is non-null// post: the object is added to the beginning of the list// post: the object is added to the beginning of the list

public void addToTail(Object anObject);public void addToTail(Object anObject);// pre: anObject is non-null// pre: anObject is non-null// post: the object is added to the end of the list// post: the object is added to the end of the list

public Object peek();public Object peek();// pre: list is not empty// pre: list is not empty// post: returns the first object in the list without // post: returns the first object in the list without // modifying the list// modifying the list

code based on Bailey pg. 99

©Duane Szafron 2000 10

Structure Interface - List 2Structure Interface - List 2

public Object tailPeek();public Object tailPeek();// pre: list is not empty// pre: list is not empty// post: returns the last object in the list without // post: returns the last object in the list without // modifying the list// modifying the list

public Object removeFromHead();public Object removeFromHead();// pre: list is not empty// pre: list is not empty// post: removes and returns first object from the list// post: removes and returns first object from the list

public Object removeFromTail();public Object removeFromTail();// pre: list is not empty// pre: list is not empty// post: removes and returns last object from the list// post: removes and returns last object from the list

code based on Bailey pg. 99

©Duane Szafron 2000 11

List Example - Free-ListsList Example - Free-Lists

One common application of Lists is as One common application of Lists is as a container to hold objects that can be a container to hold objects that can be used for a while in a program and then used for a while in a program and then later returned to the container for re-later returned to the container for re-use.use.

Such a container of re-usable objects Such a container of re-usable objects is called a is called a free-listfree-list..

©Duane Szafron 2000 12

Free-Lists of ArraysFree-Lists of Arrays

For example, consider a free-list that contains various For example, consider a free-list that contains various sizes of sizes of Arrays of intsArrays of ints..

When we need an array of a particular size, we When we need an array of a particular size, we remove it from the remove it from the free-listfree-list, use it until we don’t need , use it until we don’t need it anymore and add it back to the free-list.it anymore and add it back to the free-list.

We can then re-use this same array later when we We can then re-use this same array later when we need another array of the same size.need another array of the same size.

©Duane Szafron 2000 13

Free Lists of Arrays- ProblemFree Lists of Arrays- Problem There is a problem if we want to use a There is a problem if we want to use a free-list of arraysfree-list of arrays..

To remove an element from the list that is an array of a To remove an element from the list that is an array of a particular size, we need to call the particular size, we need to call the remove(Object)remove(Object) method and pass in an method and pass in an ObjectObject that is equal to the one that is equal to the one we want to remove.we want to remove.

If the free-list contained arrays, this would mean that we If the free-list contained arrays, this would mean that we would have to create another array of the same size and would have to create another array of the same size and then fill in the correct values in order to remove an array then fill in the correct values in order to remove an array from the free-list.from the free-list.

If you must create another array anyway, there is no If you must create another array anyway, there is no need to use a free-list. need to use a free-list.

©Duane Szafron 2000 14

Free Lists of Arrays- ArrayNodeFree Lists of Arrays- ArrayNode To solve this problem, we create a new class called To solve this problem, we create a new class called ArrayNodeArrayNode where each instance holds an where each instance holds an ArrayArray and an and an int sizeint size..

We define equality on this class by just comparing the We define equality on this class by just comparing the size valuessize values of two ArrayNodes. of two ArrayNodes.

To To removeremove an ArrayNode from a free-list, we create an ArrayNode that has the particular size value we are looking for, but no actual an ArrayNode from a free-list, we create an ArrayNode that has the particular size value we are looking for, but no actual array.array.

When the ArrayNode is removed from the free-list we can either discard the ArrayNode and keep the array or use the value field in When the ArrayNode is removed from the free-list we can either discard the ArrayNode and keep the array or use the value field in the ArrayNode for other purposes.the ArrayNode for other purposes.

©Duane Szafron 2000 15

Class ArrayNode 1Class ArrayNode 1

public class public class ArrayNode ArrayNode {{// An instance of this class contains an int and an array.// An instance of this class contains an int and an array.

/* Instance Variables *//* Instance Variables */protected int value;protected int value;protected int data[ ];protected int data[ ];

/* Constuctors *//* Constuctors */public ArrayNode(int value, int data[ ]) {public ArrayNode(int value, int data[ ]) {// post: The receiver has the given value and array data.// post: The receiver has the given value and array data.

this.value = value;this.value = value;this.data = data;this.data = data;

}}

code based on Bailey pg. 102

©Duane Szafron 2000 16

ClassClass ArrayNodeArrayNode 2 2

/* Methods *//* Methods */public int getValue() {public int getValue() {// post: return the value in the ArrayNode// post: return the value in the ArrayNode

return this.value;return this.value;}}

public void setValue(int newValue) {public void setValue(int newValue) {// post: the value in the ArrayNode is the new value// post: the value in the ArrayNode is the new value

this.value = newValue;this.value = newValue;}}

public int[ ] getData() {public int[ ] getData() {// post: return the array in the ArrayNode// post: return the array in the ArrayNode

return this.data;return this.data;}}

code based on Bailey pg. 102

©Duane Szafron 2000 17

Class ArrayNode 3Class ArrayNode 3

public boolean public boolean equalsequals (Object node) { (Object node) {// pre: node is non-null// pre: node is non-null// post: return true if the receiver is equal to the // post: return true if the receiver is equal to the // argument. In this case if they have the same value// argument. In this case if they have the same value

ArrayNode other;ArrayNode other;

other = (ArrayNode) node;other = (ArrayNode) node;return (this.value = other.value);return (this.value = other.value);

}}

code based on Bailey pg. 102

©Duane Szafron 2000 18

Class ArrayNode 4Class ArrayNode 4

public String public String toStringtoString () { () {// post: return my display string// post: return my display string

String result;String result;int index;int index;

result = "[value: " + this.value + " data:";result = "[value: " + this.value + " data:";if (data != null)if (data != null) for (index = 0; index < data.length; index++)for (index = 0; index < data.length; index++)

result = result + " " + data[index];result = result + " " + data[index];result = result + "]";result = result + "]";return result;return result;

}}}}

code based on Bailey pg. 102

©Duane Szafron 2000 19

List Example - Free Lists 1List Example - Free Lists 1

public classpublic class ExampleFreeListExampleFreeList {{/*This class contains the main program for an example /*This class contains the main program for an example program that uses program that uses free lists of ArrayNodes of various sizesfree lists of ArrayNodes of various sizes..

It reads lines from input. Each line contains a sequence of ints. It reads lines from input. Each line contains a sequence of ints. There are There are three kinds of input linesthree kinds of input lines. One kind is called an . One kind is called an output output lineline and it contains a single negative int. The second kind is and it contains a single negative int. The second kind is called an called an input lineinput line and it starts with two positive ints and and it starts with two positive ints and contains multiple other ints. The third kind of line is a contains multiple other ints. The third kind of line is a stop linestop line and it contains a zero. and it contains a zero.

The absolute value of the first int on a line is called anThe absolute value of the first int on a line is called an idid. On an . On an input line, the second int says input line, the second int says how many more intshow many more ints are on that are on that line. These other ints are called line. These other ints are called data intsdata ints. When an input line is . When an input line is found, an found, an ArrayNode of the proper size is removedArrayNode of the proper size is removed from the from the free list and the free list and the id intid int and and data intsdata ints are stored in it and this are stored in it and this ArrayNode is put into a data list. ArrayNode is put into a data list.

code based on Bailey pg. 103

©Duane Szafron 2000 20

List Example - Free Lists 2List Example - Free Lists 2

When an When an outputoutput lineline is found, the id int and all of the data is found, the id int and all of the data ints from the input line with the same id are displayed on the ints from the input line with the same id are displayed on the screen. The ArrayNode that contains these ints is removed screen. The ArrayNode that contains these ints is removed from the data list and the array is returned to the free list. from the data list and the array is returned to the free list.

When a When a stop linestop line is found, the is found, the program stopsprogram stops. .

When an When an output lineoutput line appears whose id has no appears whose id has no corresponding id in an ArrayNode in the data list, or when corresponding id in an ArrayNode in the data list, or when an an input lineinput line contains a number of data ints for which there contains a number of data ints for which there is no correct sized ArrayNode in the free list, the is no correct sized ArrayNode in the free list, the program program stopsstops..

code based on Bailey pg. 103

©Duane Szafron 2000 21

List Example - Free Lists 3List Example - Free Lists 3

public static void public static void main main (String args[]) {(String args[]) {List freeList;List freeList;List data;List data;ReadStream stream;ReadStream stream;boolean success;boolean success;

freeList = makeFreeList();freeList = makeFreeList();data = data = newnew SinglyLinkedList(); SinglyLinkedList();stream = stream = newnew ReadStream(); ReadStream();success = true;success = true;while (success) while (success) // success fails when stop // success fails when stop

occursoccurs success = nextLine(stream, data, freeList);success = nextLine(stream, data, freeList);

}}code based on Bailey pg. 103

©Duane Szafron 2000 22

Example InputExample Input

1 2 68 37

4 5 2 4 6 8 10

-4

-5

3 2 36 85

9 2 14 15

6837

1

24

4

68

10

Display Display id=4 data=(2,4,6,8,10)

3685

3

STOPSTOPSTOPSTOP

©Duane Szafron 2000 23

List Example - Free Lists 4List Example - Free Lists 4

public static List public static List makeFreeListmakeFreeList () { () {// post: return a free list containing 2 ArrayNodes of// post: return a free list containing 2 ArrayNodes of// each size:2 to 10 inclusive// each size:2 to 10 inclusive..

List freeList;List freeList; int index;int index;

freeList = freeList = newnew SinglyLinkedList(); SinglyLinkedList(); for (index = 1; index < 11; index++) {for (index = 1; index < 11; index++) {

freeList.add(new ArrayNode(index, new int[index]));freeList.add(new ArrayNode(index, new int[index])); freeList.add(new ArrayNode(index, new int[index]));freeList.add(new ArrayNode(index, new int[index]));

}} return freeList;return freeList;}}

code based on Bailey pg. 103

©Duane Szafron 2000 24

Illustrating the List StructureIllustrating the List Structure

1 102 3

freeList - a list of ArrayNodefreeList - a list of ArrayNode

1

23

10

1

dataListdataList

©Duane Szafron 2000 25

List Example - Free Lists 5List Example - Free Lists 5public static boolean public static boolean nextLinenextLine (Stream stream, List data, (Stream stream, List data,

List freeList) {List freeList) {// pre: data, stream and freeList are non-null// pre: data, stream and freeList are non-null/* post: read an int from the stream. If the/* post: read an int from the stream. If the int is positiveint is positive, , process an input line and return true if it was successful and process an input line and return true if it was successful and false otherwise. If thefalse otherwise. If the int is negativeint is negative, , process an output line process an output line and return true if it was successful and false otherwise.and return true if it was successful and false otherwise. If theIf the int was zeroint was zero, return false. */, return false. */

int id; boolean success;int id; boolean success; stream.skipWhite(); id = stream.readInt();stream.skipWhite(); id = stream.readInt(); ifif (id > 0) success = input (id, stream, data, freeList);(id > 0) success = input (id, stream, data, freeList); else if (id < 0) success = output (-id, data, freeList);else if (id < 0) success = output (-id, data, freeList);

else success = false; else success = false; //stop condition reached//stop condition reached return success;return success;}}

code based on Bailey pg. 103

©Duane Szafron 2000 26

List Example - Free Lists 6List Example - Free Lists 6

public static boolean public static boolean inputinput (int id, ReadStream stream, (int id, ReadStream stream, List data, List freeList) {List data, List freeList) {

// pre: id > 0, stream and freeList are non-null// pre: id > 0, stream and freeList are non-null/* post: read an int from the stream. If the/* post: read an int from the stream. If the int is not positiveint is not positive, return , return false. Otherwise, find an ArrayNode in the free list that is the size false. Otherwise, find an ArrayNode in the free list that is the size of this int. If none exists return false. If one exists, read that many of this int. If none exists return false. If one exists, read that many ints into the array, move the ArrayNode to the data list, using the ints into the array, move the ArrayNode to the data list, using the value field for the id and return true. */value field for the id and return true. */

int count;int count;ArrayNode node;ArrayNode node;

stream.skipWhite();stream.skipWhite();count = stream.readInt();count = stream.readInt();if (count <= 0)if (count <= 0)

return false;return false;code based on Bailey pg. 104

©Duane Szafron 2000 27

List Example - Free Lists 7List Example - Free Lists 7

node = new ArrayNode(count, null);node = new ArrayNode(count, null); // Now remove node from freeList if one exists// Now remove node from freeList if one exists

node = (ArrayNode) freeList.remove(node);node = (ArrayNode) freeList.remove(node);if (node == null)if (node == null) return false;return false;node.setValue(id);node.setValue(id);readData(count, stream, node.getData());readData(count, stream, node.getData());data.add(node);data.add(node);return true;return true;

}}

code based on Bailey pg. 103

©Duane Szafron 2000 28

List Example - Free Lists 8List Example - Free Lists 8

public static void public static void readData readData (int size, ReadStream (int size, ReadStream stream, int anArray[]) {stream, int anArray[]) {

// pre: size > 0, stream is non-null, anArray.length >= size// pre: size > 0, stream is non-null, anArray.length >= size// post: read size number of ints from the stream to the array// post: read size number of ints from the stream to the array

int index;int index;

Assert.pre((size > 0) && Assert.pre((size > 0) && (anArray.length >= size) && (anArray.length >= size) &&

(stream != null), “Array too small”); (stream != null), “Array too small”); for (index = 0; index < size; index++) {for (index = 0; index < size; index++) { stream.skipWhite();stream.skipWhite(); anArray[index] = stream.readInt();anArray[index] = stream.readInt();}}

}}

©Duane Szafron 2000 29

List Example - Free Lists 9List Example - Free Lists 9

public static boolean public static boolean output output (int id, List data, List freeList) {(int id, List data, List freeList) {// pre: data and freeList are non-null// pre: data and freeList are non-null// post: Find the ArrayNode in the data list with the given id as// post: Find the ArrayNode in the data list with the given id as// its value. If it is not found, return false. Otherwise, output// its value. If it is not found, return false. Otherwise, output// the ArrayNode, change the value of the ArrayNode to the length // the ArrayNode, change the value of the ArrayNode to the length // of its array and transfer it from the data list to the free list.// of its array and transfer it from the data list to the free list.

ArrayNode node;ArrayNode node;node = new ArrayNode(id, null);node = new ArrayNode(id, null);node = (ArrayNode) data.remove(node);node = (ArrayNode) data.remove(node);if (node == null) return false; if (node == null) return false; // no match with existing node// no match with existing node

System.out.println(node);System.out.println(node);node.setValue(node.getData().length); node.setValue(node.getData().length); // find length of// find length of

// existing node// existing node

freeList.add(node);freeList.add(node);return true;return true;

}} code based on Bailey pg. 104