Presentation is loading. Please wait.

Presentation is loading. Please wait.

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java From Control Structures through Data Structures by.

Similar presentations


Presentation on theme: "Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java From Control Structures through Data Structures by."— Presentation transcript:

1 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java From Control Structures through Data Structures by Tony Gaddis and Godfrey Muganda Chapter 19: Array-Based Lists

2 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 2 Chapter Topics Introduction to Lists Creating an Array-Based List Creating a Generic Array-Based List Iterators and Iterable Lists

3 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 3 Introduction to Lists A list is a collection that stores its elements in a sequential order. Every element in a sequence has an integer index that gives its position in the sequence.

4 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 4 Predecessors and Successors The first element in the list has index = 0. Every element on the list other than the first has a predecessor: the element immediately before it in the list. Every element on the list other than the first has a successor: the element immediately after it in the list.

5 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 5 Indices of Predecessors and Successors Let x be an element on a list, and let x have index k. If x is not the last element on the list, the successor of x will have index k + 1. If x is not the first item on the list, the predecessor of x will have index k -1.

6 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 6 List Operations A list collection will usually support a number of operations, based on the value of an object stored, and / or its index within the list.

7 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 7 Common List Operations boolean add(E o) void add(int index, E element) void clear() boolean contains(Object o) E get(int index) int indexOf(Object o) boolean isEmpty() E remove(int index) boolean remove(Object o)

8 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 8 Creating a String List Class

9 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 9 The StringList Interface public interface StringList { public void add(String str); public void add(int index, String str); public void clear(); public boolean contains(String str); public String get(int index); public int indexOf(String str); public boolean isEmpty(); public boolean remove(String str); public String remove(int index); public String set(int index, String str); public int size(); }

10 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 10 Implementing a String List Class The implementation is based on a resizable array: // Constants for the default capacity and // the resizing factor. private final int DEFAULT_CAPACITY = 10; private final int RESIZE_FACTOR = 2; // Private Fields private String[] list; // The list private int elements; // Number of elements stored

11 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 11 Constructing the List Object /** This constructor creates an empty list of the default capacity. */ public StringListType() { list = new String[DEFAULT_CAPACITY]; elements = 0; }

12 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12 Implementing the Resizable Array Storage As elements are added, the array used to store the elements may fill up. We need a method that will create a new bigger array, copy the list elements to the bigger array, and make the new array the store for the list.

13 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 13 Implementing the Resizable Array Storage /** Resizes the list to twice its current length. */ private void resize() { // Calculate the new length, which is the current // length multiplied by the resizing factor. int newLength = list.length * RESIZE_FACTOR; // Create a new list. String[] tempList = new String[newLength]; // Copy the existing elements to the new list. for (int index = 0; index < elements; index++) tempList[index] = list[index]; // Replace the existing list with the new one. list = tempList; }

14 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 14 Determining the size of the List public int size() { return elements; }

15 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 15 Determining if the List is empty public boolean isEmpty() { return (elements == 0); }

16 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 16 Adding a String to the End of the List /** Add a string to the end of the list. */ public void add(String str) { // If the list is full, resize it. if (elements == list.length) resize(); // Add str to the end of the list. list[elements] = str; // Adjust the number of elements. elements++; }

17 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 17 Adding a String at a Given Index public void add(int index, String str) { // First make sure the index is valid. if (index > elements || index < 0) throw new IndexOutOfBoundsException(); // If the list is full, resize it. if (elements == list.length) resize(); // Shift the elements starting at index // to the right one position. for (int index2 = elements; index2 > index; index2--) list[index2] = list[index2 - 1]; // Add the new element at index. list[index] = str; // Adjust the number of elements. elements++; }

18 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 18 Checking List Membership public boolean contains(String str) { int index = 0; // Index counter boolean found = false; // Search flag // Step through the list. When the string // is found, set found to true and stop. while (!found && index < elements) { if (list[index].equals(str)) found = true; index++; } // Return the status of the search. return found; }

19 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 19 Retrieving an Element Based on its Index public String get(int index) { if (index >= elements || index < 0) throw new IndexOutOfBoundsException(); return list[index]; }

20 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 20 Retrieving the Index of an Element public int indexOf(String str) { int index = 0; // Index counter boolean found = false; // Search flag // Step through the list. When the string // is found, set found to true and stop. while (!found && index < elements) { if (list[index].equals(str)) found = true; else index++; } // Return the index of str or -1. if (!found) index = -1; return index; }

21 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 21 Removing an Element public boolean remove(String str) { // Search index and flag int index = 0; boolean found = false; // Perform a sequential search for str. When it is found, remove it and stop searching. while (!found && index < elements) { if (list[index].equals(str)) { list[index] = null; found = true; } index++; } // If the value was found, shift all subsequent elements toward the front of the list. if (found) { while(index < elements) { list[index - 1] = list[index]; index++; } // Adjust the number of elements. elements--; } return found; }

22 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 22 Removing an Element Based on Index public String remove(int index) { if (index >= elements || index < 0) throw new IndexOutOfBoundsException(); // Save the string, but remove it from the list. String temp = list[index]; list[index] = null; index++; // Shift all subsequent elements toward the front of the list. while(index < elements) { list[index - 1] = list[index]; index++; } // Adjust the number of elements. elements--; // Return the string that was removed. return temp; }

23 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 23 Replacing the Element at an Index public String set(int index, String str) { if (index >= elements || index < 0) throw new IndexOutOfBoundsException(); // Save the existing string at that index. String temp = list[index]; // Replace the string with str. list[index] = str; // Return the previously stored string. return temp; }

24 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 24 Clearing the List public void clear() { for (int index = 0; index < list.length; index++) list[index] = null; elements = 0; }

25 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 25 Creating a Generic Array-Based List

26 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 26 Creating a Generic Array-Based List Creating a generic list is very similar to creating a string list. Almost all the modifications consist of changing the type of variables and parameters from String to a type parameter.

27 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 27 The Interface for a Generic List public interface GeneralList { public void add(E element); public void add(int index, E element); public boolean contains(E element); public E get(int index); public int indexOf(E element); public boolean isEmpty(); public boolean remove(E element); public E remove(int index); public E set(int index, E element); public int size(); }

28 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 28 Implementation of the Generic Class public class ListType implements GeneralList { // Constants for the default capacity and // the resizing factor. private final int DEFAULT_CAPACITY = 10; private final int RESIZE_FACTOR = 2; // Private Fields private E[] list; // The list private int elements; // Number of elements stored }

29 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 29 Creating the Arrays Java does not allow creation of arrays of generic type, so we have to create an array of Object and cast it to the generic type: public ListType() { list = (E[ ]) (new Object[DEFAULT_CAPACITY]); elements = 0; }

30 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 30 Implementation of Generic List Methods Modify all methods to use type parameter E in place of String, for example: public void add(E element) { // If the list is full, resize it. if (elements == list.length) resize(); // Add element to the end of the list. list[elements] = element; // Adjust the number of elements. elements++; }

31 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 31 Iterators and Iterable Lists Iterators provide a systematic way of accessing all elements stored in a collection. A collection is iterable if it is capable of providing an iterator that can be used to access elements stored in it.

32 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 32 Iterable Collections A collection class becomes iterable by implementing the Iterable interface interface Iterable { public Iterator iterator() } The one method in the Iterable interface returns an iterator for the collection.

33 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 33 Iterators An iterator must implement the following methods –boolean hasNext() : Is there another element in the collection that can be returned? –E next() : return the next available element. –void remove() : remove the item returned by the last call to next(), This method can only be called once for each call to next().

34 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 34 Implementing an Iterator What type of information does an iterator need to do its job? – what collection or list to iterate over. – a cursor position : the index of the list element that was returned by the last call to next(). – a can-remove flag to indicate when it is permissible to call remove().

35 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 35 Fields for a Generic List Iterator public class ListTypeIterator implements Iterator { private GeneralList list; // The list to iterate over private int previous; // The previous element boolean canRemove; // Flag to manage removals }

36 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 36 The Constructor The constructor for the list iterator is passed a reference to the list to be iterated over. The constructor initializes the previous index to - 1, and the canRemove flag to false.

37 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 37 Initializing the Iterator public ListTypeIterator(GeneralList aList) { // Save the list reference. list = aList; // By setting previous to -1, we are positioning // the iterator just before the first element. previous = -1; // We set the canRemove field to false. The remove // method can only be called after the next method // has been called. canRemove = false; }

38 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 38 hasNext() public boolean hasNext() { if ((previous + 1) < list.size()) return true; else return false; }

39 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 39 next() public E next() { // If there are no more elements, throw an exception. if (!hasNext()) throw new NoSuchElementException(); // Adding one to previous gives us the index of // the next element in the list. previous++; // Set canRemove to true to indicate that the remove // method can be called. canRemove = true; // Return the list element. return list.get(previous); }

40 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 40 remove() public void remove() { // We can only call remove after next has been called. if (!canRemove) throw new IllegalStateException(); // Remove the previous element. list.remove(previous); // Adjust previous. previous--; // Reset the canRemove field. You can only call remove // once per call to next. canRemove = false; }

41 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 41 Iterator Demo public static void main(String[] args) { // Create a list to hold String objects and add some names ListType nameList = new ListType (); nameList.add("Johnson"); nameList.add("Graves"); nameList.add("Smith"); nameList.add("Jones"); // Get an iterator. Iterator firstIt = nameList.iterator(); // Use the iterator to search for "Smith" and remove it from the list. while (firstIt.hasNext()) { if (firstIt.next().equals("Smith")) firstIt.remove(); } // Get another iterator. Iterator secondIt = nameList.iterator(); // Use the iterator to display elements in the list. Smith has been removed. while (secondIt.hasNext()) System.out.println(secondIt.next()); }

42 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 42 Implementing an Iterable List A list class can be made iterable by implementing the Iterable interface: public class ListType implements GeneralList, Iterable { public Iterator iterator() { return new ListTypeIterator (this); }


Download ppt "Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java From Control Structures through Data Structures by."

Similar presentations


Ads by Google