List Implementations That Use Arrays

Slides:



Advertisements
Similar presentations
Chapter 25 Lists, Stacks, Queues, and Priority Queues
Advertisements

CS Data Structures I Chapter 6 Stacks I 2 Topics ADT Stack Stack Operations Using ADT Stack Line editor Bracket checking Special-Palindromes Implementation.
Copyright © 2002 Pearson Education, Inc. Slide 1.
Chapter 7 Constructors and Other Tools. Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 7-2 Learning Objectives Constructors Definitions.
Chapter 6 Structures and Classes. Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 6-2 Learning Objectives Structures Structure types Structures.
Copyright © 2003 Pearson Education, Inc. Slide 1.
Introduction to Computation and Problem
11 Copyright © 2005, Oracle. All rights reserved. Using Arrays and Collections.
10 Copyright © 2005, Oracle. All rights reserved. Reusing Code with Inheritance and Polymorphism.
15 Copyright © 2005, Oracle. All rights reserved. Adding User Interface Components and Event Handling.
Lecture 15 Linked Lists part 2
Chapter 17 Linked Lists.
Topic 12 The List ADT. 9-2 Objectives Examine list processing and various ordering techniques Define a list abstract data type Examine various list implementations.
Chapter 4 Linked Lists. © 2005 Pearson Addison-Wesley. All rights reserved4-2 Preliminaries Options for implementing an ADT List –Array has a fixed size.
Linked Lists Chapter 4.
Data Structures: A Pseudocode Approach with C
Data Structures ADT List
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.
Lists Chapter 8 Data Structures and Problem Solving with C++: Walls and Mirrors, Carrano and Henry, © 2013.
ITEC200 Week04 Lists and the Collection Interface.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Ver Chapter 4: Linked Lists Data Abstraction & Problem Solving with.
Data Structures Using C++
1 CompSci 105 SS 2005 Principles of Computer Science Lecture 11: Linked Lists Lecturer: Santokh Singh Assignment 2 due tomorrow, i.e. Friday 21 Jan 2005.
COSC 1P03 Data Structures and Abstraction 10.1 The List If A is success in life, then A equals x plus y plus z. Work is x; y is play; and z is keeping.
Double-Linked Lists and Circular Lists
John Hurley Cal State LA
Chapter 1 Object Oriented Programming 1. OOP revolves around the concept of an objects. Objects are created using the class definition. Programming techniques.
1 Joe Meehean. Ordered collection of items Not necessarily sorted 0-index (first item is item 0) Abstraction 2 Item 0 Item 1 Item 2 … Item N.
Lists Chapter 4 Carrano, Data Structures and Abstractions with Java, Second Edition, (c) 2007 Pearson Education, Inc. All rights reserved X.
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Hash Tables,
1 public class Newton { public static double sqrt(double c) { double epsilon = 1E-15; if (c < 0) return Double.NaN; double t = c; while (Math.abs(t - c/t)
The List ADT Textbook Sections
Copyright © 2013 by John Wiley & Sons. All rights reserved. HOW TO CREATE LINKED LISTS FROM SCRATCH CHAPTER Slides by Rick Giles 16 Only Linked List Part.
©Brooks/Cole, 2001 Chapter 12 Derived Types-- Enumerated, Structure and Union.
PSSA Preparation.
Java POWERED BY: ARVIND DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING RADHA GOVIND GROUP OF INSTITUTIONS,MEERUT.
Abstraction, Modularity, Interfaces and Pointers Original slides by Noah Mendelsohn, including content from Mark Sheldon, Noah Daniels, Norman Ramsey COMP.
Chapter 9: Using Classes and Objects. Understanding Class Concepts Types of classes – Classes that are only application programs with a Main() method.
Linked Lists Compiled by Dr. Mohammad Alhawarat CHAPTER 04.
Designing an ADT The design of an ADT should evolve naturally during the problem-solving process Questions to ask when designing an ADT What data does.
An Array-Based Implementation of the ADT List public class ListArrayBased implements ListInterface { private static final int MAX_LIST = 50; private Object.
Completing the Linked Implementation of a List Chapter 7 Slides by Steve Armstrong LeTourneau University Longview, TX  2007,  Prentice Hall.
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.
List Implementations That Use Arrays Chapter 5 Slides by Steve Armstrong LeTourneau University Longview, TX  2007,  Prentice Hall.
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.
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.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 10 *Arrays with more than one dimension *Java Collections API.
List Implementations That Link Data Chapter 6. 2 Chapter Contents Linked Data Forming a Chains The Class Node A Linked Implementation Adding to End of.
Arrays, Loops weeks 4-6 (change from syllabus for week 6) Chapter 4.
Bag Implementations that Use Arrays Chapter 2 Copyright ©2012 by Pearson Education, Inc. All rights reserved.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Lists Ellen Walker CPSC 201 Data Structures Hiram College.
5-Aug-2002cse Arrays © 2002 University of Washington1 Arrays CSE 142, Summer 2002 Computer Programming 1
Lists Chapter 4. 2 Chapter Contents Specifications for the ADT List Redefining the Specifications Using the ADT List Java Class Library: The Interface.
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.
Bag Implementations that Use Arrays Chapter 2 © 2015 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures and Abstractions.
Lecture 9: Lists MIT-AITI Kenya © 2005 MIT-Africa Internet Technology Initiative In this lecture we will learn…. ArrayList – These are re-sizeable.
JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN © 2012 Pearson Education, Inc., Upper Saddle River,
Lists and Sorted Lists: various implementations Slides by Nadia Al-Ghreimil adopted from Steve Armstrong LeTourneau University Longview, TX  2007, 
1 CS162: Introduction to Computer Science II Abstract Data Types.
An Array-Based Implementation of the ADT List
Lists Chapter 4.
Bag Implementations that Use Arrays
Dynamic Data Structures and Generics
List Implementations that Use Arrays
Recitation 2 CS0445 Data Structures
List Implementations that Use Arrays
© 2016 Pearson Education, Ltd. All rights reserved.
Presentation transcript:

List Implementations That Use Arrays Chapter 5

Exercise key a. int positionOfSmallest ; double smallest, toCompare; int count = quizScores.getLength(); if (count > 0) { positionOfSmallest = 1; smallest = quizScores.getEntry(1); for (int i = 2; i <= count; i++) toCompare = quizScores.getEntry(i); if (toCompare < smallest) smallest=toCompare; positionOfSmallest = i; } // end if } // end for quizScores.removeEntry(positionOfSmallest); }

Exercise key b. double sum = 0.0; double score; double average = 0.0; int count = quizScores.getLength(); if (count > 0) { for (int i = 1; i <= count; i++) score = quizScores.getEntry(i); sum += score; } // end for average = sum / count; } // end if

Chapter Contents Using a Fixed-Size Array to Implement the ADT List An Analogy The Java Implementation Using Dynamic Array Expansion to Implement the ADT List Expanding an Array A News Implementation of a List Using a Vector to Implement the ADT List A Summary of Methods in the Class Vector The Pros and Cons of Using an Array to Implement the ADT List The Class ArrayList The Interface Serializable

An Analogy Consider a classroom with 40 desks in fixed position Desks are wasted if less than 40 students Not enough desks if more than 40 students An array is like the classroom Each desk an array location

A classroom that contains desks in a fixed position. An Analogy A classroom that contains desks in a fixed position.

An Analogy Suppose we have some students in classroom in order alphabetically We add a new student We desire to maintain the alphabetic order We must shift some students We remove a student in the middle of the sequence Again, we must shift some students

Adding a Student Seating a new student between two existing students: at least one other student must move

The Java Implementation Private data fields for implementation of AList Implements interface ListInterface of Chapter 4 public class AList<T> implements ListInterface<T> { private T[] list; // array of list entries private int length; // current number of entries in list private static final int MAX_SIZE = 50; // max length of list

The Java Implementation public AList() { this(Max_SIZE); } public AList(int maxSize) Length = 0; list = (T[]) new Object [maxSize]; public void clear() length = 0;

The Java Implementation public boolean isEmpty() { return length == 0; } public boolean isFull() return length == list.length; public void display() for ( int index = 0; index < length; index++) system.out.println(list[index]);

AList add() Methods First add method adds a new item at the end of the list Assign new value at end Increment length of list Second add method adds item in mid-list Requires a utility method, makeRoom() This shifts elements backwards

Adding Items in Mid-list Making room to insert Carla as third entry in an array.

Add Method public boolean add( T newEntry) { boolean isSuccessful = true; if (!isFull()) list[length] = newEntry; length++; } else isSuccessful = false; return isSuccessful;

Another Add Method public boolean add( int newPosition, T newEntry) { boolean isSuccessful = true; if (!isFull() && (newPosition >= 1) && (newPosition <= length +1) ) makeRoom(newPosition); list[newPosition -1] = newEntry; length++; } else isSuccessful = false; return isSuccessful;

makeRoom Method private void makeRoom( int newPosition) { assert (newPosition >=1) && (newPosition <= length +1); int newIndex = newPosition -1; int lastIndex = length -1; // move each entry to higher next higher index starting at the end continuing // until the entry at newIndex is moved for ( int index = lastIndex; index >= newIndex; index--) list[index +1] = list[index]; }

Questions? 1). Suppose that myList is a list that contains the five entries a b c d e. a. what does myList contain after executing myList.add(5, w)? b. Starting with the original five entries, what does myList contain after executing myList.add(6,w)? c. Which of the operations in a and b of this question require elements in the array to shift?

Questions? 2). If myList is a list of five entries, each of the following statements adds a new entry to the end of the list: myList.add(newEntry); myList.add(6, newEntry); Which way requires fewer operations?

The remove() Method Must shift existing entries to avoid gap in the array Except when removing last entry Method must also handle error situation When position specified in the remove is invalid When remove() is called and the list is empty Invalid call returns null value

Removing Bob by shifting array entries. Removing a List Entry Removing Bob by shifting array entries.

Remove Method public T remove( int givenPosition) { T result = null; // return value if ((givenPosition >= 1) && (givenPosition <= length)) assert !isEmpty(); result = list[givenPosition -1]; // get entry to be removed. if (givenPosition < length) // move subsequent entries toward entry to be removed unless it is last in list removeGap(givenPostion); length--; } // return reference to removed entry, or null if empty or givenPosition is invalid. return result;

removeGap Method private void removeGap( int givenPosition) { assert (givenPosition >= 1) && (givenPosition < length); int removedIndex = givenPosition -1; int lastIndex = length -1; for ( int index = removedIndex; index < lastIndex; index++) list[index] = list[index +1]; } Question: Previous remove figure shows Haley shifted toward the beginning of the array. Actually, the reference to Haley is copied, not moved, to its new location. Should we assign null to Haley’s original location?

Dynamic Array Expansion An array has a fixed size If we need a larger list, we are in trouble When array becomes full Move its contents to a larger array (dynamic expansion) Copy data from original to new location Manipulate names so new location keeps name of original array

Dynamic Array Expansion (a) an array; (b) the same array with two references; (c) the two arrays, reference to original array now referencing a new, larger array

Dynamic Array Expansion The dynamic expansion of an array copies the array's contents to a larger second array.

Dynamic Array Expansion Let’s work with a simple array of integers: int[] myArray = new int[INITIAL_SIZE]; // save reference to myArray int[] oldArray = myArray; // double the size of array myArray = new int[2 * oldArray.length]; // copy the data from the old array to the new array for ( int index = 0; index < oldArray.length; index++) myArray[index] = oldArray[index]; //for a generic data type private void doubleArray() { T[] oldList = list; int oldSize = oldList.length; list = (T[]) new Object[2 * oldSize]; for ( int index = 0; index < oldSize; index++) list[index] = oldList[index]; }

A New Implementation of a List Change the isFull to always return false We will expand the array when it becomes full We keep this function so that the original interface does not change The add() methods will double the size of the array when it becomes full Now declare a private method isArrayFull Called by the add() methods

Using a Vector to Implement the ADT List Java's Vector class provides capabilities of an array Able to expand dynamically Hides the details of the process Vector Found in package java.util Has methods for manipulating entries Implementing the ADT List

Using a Vector A client uses the methods given in ListInterface, but the implementation of the list uses Vector methods to perform its operations

Using a Vector Elements of the class Class Vector comes from package java.util Data field list is an instance of a Vector We can directly call Vector’s methods to implement the methods declared in the ListInterface. import java.util.Vector; public class VectorList<T> implements ListInterface { private Vector<T> list; // entries in list . . .

Using a Vector The add() methods The remove() method The first uses the add method from the Vector class. list.add(newEntry); The other uses an overloaded add method. list.add(newPosition, newEntry); The remove() method Uses the remove method. list.remove(givenPosition);

Pros and Cons of Array Use for the ADT List When using an array or vector … Retrieving an entry is fast Adding an entry at the end of the list is fast Adding or removing an entry that is between other entries requires shifting elements in the array Increasing the size of the array or vector requires copying elements

Java Class Library Has a class similar to class AList defined in this chapter Class ArrayList Uses dynamic array expansion