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

Slides:



Advertisements
Similar presentations
Lists and the Collection Interface Chapter 4. Chapter Objectives To become familiar with the List interface To understand how to write an array-based.
Advertisements

CSC 205 – Java Programming II Lecture 25 March 8, 2002.
© 2006 Pearson Addison-Wesley. All rights reserved5 A-1 Chapter 5 Linked Lists CS102 Sections 51 and 52 Marc Smith and Jim Ten Eyck Spring 2008.
An Array-Based Implementation of the ADT List public class ListArrayBased implements ListInterface { private static final int MAX_LIST = 50; private Object.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 10 Using arrays to create collections.
CSE 143 Lecture 22: Advanced List Implementation (ADTs; interfaces; abstract classes; inner classes; generics; iterators)
Lists Chapter 4. 2 Chapter Contents Specifications for the ADT List Redefining the Specifications Using the ADT List Using a List Is Like Using a Vending.
CS 106 Introduction to Computer Science I 05 / 03 / 2010 Instructor: Michael Eckmann.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Sixth Edition Chapter 17: Linked Lists.
List Implementations That Use Arrays Chapter 5. 2 Chapter Contents Using a Fixed-Size Array to Implement the ADT List An Analogy The Java Implementation.
CHAPTER 6 Stacks Array Implementation. 2 Stacks A stack is a linear collection whose elements are added and removed from one end The last element to be.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Sixth Edition Chapter 18: Stacks and.
12-Jul-15 Lists in Java Part of the Collections Framework.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 10 Using arrays to create collections.
CS 106 Introduction to Computer Science I 04 / 30 / 2010 Instructor: Michael Eckmann.
Arrays And ArrayLists - S. Kelly-Bootle
Topic 3 The Stack ADT.
Announcements  I will discuss the labtest and the written test #2 common mistakes, solution, etc. in the next class  not today as I am still waiting.
04/29/ Introduction to Vectors?... A vector is a dynamic array. - It can be expanded and shrunk as required - A Component of a vector can be accessed.
Generalized Containers CSIS 3701: Advanced Object Oriented Programming.
Information and Computer Sciences University of Hawaii, Manoa
Lists Ellen Walker CPSC 201 Data Structures Hiram College.
IMPLEMENTING ARRAYLIST – Part 2 COMP 103. RECAP  Abstract Classes – overview, details in 2 nd year  Implementing the ArrayList: size(), get(), set()
Data Design and Implementation. Definitions of Java TYPES Atomic or primitive type A data type whose elements are single, non-decomposable data items.
Arrays Construct array: new double[10] Store in variable of type double[] double[] data = new double[10];
Information and Computer Sciences University of Hawaii, Manoa
April 24, 2017 Chapter 4 Data Abstraction The Walls
ArrayList Class An ArrayList is an object that contains a sequence of elements that are ordered by position. An ArrayList is an object that contains a.
(c) University of Washington15-1 CSC 143 Java List Implementation via Arrays Reading: 13.
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures for Java William H. Ford William R. Topp Chapter 13 Implementing.
1 Collection, Iterable, and Iterator Interfaces The Collection Interface and its Hierarchy The Iterable and Iterator Interfaces For-each Loops with Iterable.
Aug 9, CMSC 202 ArrayList. Aug 9, What’s an Array List ArrayList is  a class in the standard Java libraries that can hold any type of object.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Chapter 16 – Basic Data Structures.
Chapter 2 Collections. Copyright © 2004 Pearson Addison-Wesley. All rights reserved.1-2 Chapter Objectives Define the concept and terminology related.
CS 367 Introduction to Data Structures Lecture 2 Audio for Lecture 1 is available Homework 1 due Friday, September 18.
© 2006 Pearson Addison-Wesley. All rights reserved5 B-1 Chapter 5 (continued) Linked Lists.
Course: Object Oriented Programming - Abstract Data Types Unit2: ADT ListsSlide Number 1 Principles for implementing ADTs ADT operations as “walls” between.
Copyright © 0 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java From Control Structures through Data Structures by Tony.
Chapter 5 Array-Based Structures © 2006 Pearson Education Inc., Upper Saddle River, NJ. All rights reserved.
IMPLEMENTING ARRAYLIST COMP 103. RECAP  Comparator and Comparable  Brief look at Exceptions TODAY  Abstract Classes - but note that the details are.
ArrayList JavaMethods An Introduction to Object-Oriented Programming Maria Litvin Gary Litvin Copyright © 2003 by Maria Litvin, Gary Litvin, and Skylight.
Copyright © Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java From Control Structures through Data Structures by Tony.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy.
© 2010 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of CHAPTER 15: Sets and Maps Java Software Structures: Designing and Using.
Data Structures I Collection, List, ArrayList, LinkedList, Iterator, ListNode.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Chapter 18 List ADT Animated Version.
Collections Dwight Deugo Nesa Matic
M180: Data Structures & Algorithms in Java Stacks Arab Open University 1.
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures for Java William H. Ford William R. Topp Chapter 20 Ordered.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy.
Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Eighth Edition by Tony Gaddis,
1 The copy constructor in the BankAccounts class. Two alternatives here: /** copy constructor */ public BankAccounts(BankAccounts L){ theAccounts = L.theAccounts.clone();
Implementing ArrayList Part T2 Lecture 6 School of Engineering and Computer Science, Victoria University of Wellington  Thomas Kuehne, Marcus Frean,
19-Mar-16 Collections and ArrayLists.. 2 Collections Why use Collections. Collections and Object-Orientation. ArrayLists. Special Features. Creating ArrayLists.
Quiz: Design a Product Class Create a definition for a class called Product, which keeps track of the following information: –Name of the product –Weight.
Copyright © 2013 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Programming Logic & Design Third Edition by Tony Gaddis.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java From Control Structures through Data Structures by.
 2016, Marcus Biel, ArrayList Marcus Biel, Software Craftsman
1 CS162: Introduction to Computer Science II Abstract Data Types.
Linked Lists Chapter 5 (continued)
COP 3503 FALL 2012 Shayan Javed Lecture 8
Implementing ArrayList Part 1
TCSS 143, Autumn 2004 Lecture Notes
Programming in Java Lecture 11: ArrayList
ArrayLists 22-Feb-19.
Collections Framework
Linked Lists Chapter 5 (continued)
Linked Lists Chapter 5 (continued)
Presentation transcript:

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

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

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.

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.

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.

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.

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)

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

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(); }

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

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; }

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.

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; }

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

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

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++; }

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++; }

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; }

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]; }

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; }

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; }

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; }

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; }

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; }

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

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.

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(); }

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 }

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; }

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++; }

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.

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.

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().

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().

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 }

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.

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; }

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; }

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); }

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; }

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()); }

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); }