(c) University of Washington15-1 CSC 143 Java List Implementation via Arrays Reading: 13.

Slides:



Advertisements
Similar presentations
Chapter 22 Implementing lists: linked implementations.
Advertisements

Chapter 23 Organizing list implementations. This chapter discusses n The notion of an iterator. n The standard Java library interface Collection, and.
Why not just use Arrays? Java ArrayLists.
Singly linked lists Doubly linked lists
DATA STRUCTURES USING C++ Chapter 5
Linked Lists Linear collections.
AITI Lecture 19 Linked List Adapted from MIT Course 1.00 Spring 2003 Lecture 26 and Tutorial Note 9 (Teachers: Please do not erase the above note)
The List ADT Textbook Sections
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java From Control Structures through Data Structures by.
CSC 205 – Java Programming II Lecture 25 March 8, 2002.
An Array-Based Implementation of the ADT List public class ListArrayBased implements ListInterface { private static final int MAX_LIST = 50; private Object.
CSE 143 Lecture 22: Advanced List Implementation (ADTs; interfaces; abstract classes; inner classes; generics; iterators)
Iterators Chapter 7. Chapter Contents What is an Iterator? A Basic Iterator Visits every item in a collection Knows if it has visited all items Doesn’t.
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.
CS 106 Introduction to Computer Science I 04 / 30 / 2010 Instructor: Michael Eckmann.
(c) University of Washingtonhashing-1 CSC 143 Java Hashing Set Implementation via Hashing.
Topic 3 The Stack ADT.
Implementing Stacks Ellen Walker CPSC 201 Data Structures Hiram College.
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.
(c) University of Washington14-1 CSC 143 Java Collections.
ArrayList, Multidimensional Arrays
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()
Ordered Containers CMPUT Lecture 19 Department of Computing Science University of Alberta ©Duane Szafron 2003 Some code in this lecture is based.
1/20/03A2-1 CS494 Interfaces and Collection in Java.
ICOM 4035 – Data Structures Lecture 3 – Bag ADT Manuel Rodriguez Martinez Electrical and Computer Engineering University of Puerto Rico, Mayagüez ©Manuel.
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.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures for Java William H. Ford William R. Topp Chapter 13 Implementing.
“Never doubt that a small group of thoughtful, committed people can change the world. Indeed, it is the only thing that ever has.” – Margaret Meade Thought.
Chapter 5 Array-Based Structures © 2006 Pearson Education Inc., Upper Saddle River, NJ. All rights reserved.
(c) University of Washington16-1 CSC 143 Java Linked Lists Reading: Ch. 20.
(c) University of Washington16-1 CSC 143 Java Lists via Links Reading: Ch. 23.
CSS446 Spring 2014 Nan Wang.  To understand the implementation of linked lists and array lists  To analyze the efficiency of fundamental operations.
Ordered Linked Lists using Abstract Data Types (ADT) in Java Presented by: Andrew Aken.
CS 367 Introduction to Data Structures Lecture 2 Audio for Lecture 1 is available Homework 1 due Friday, September 18.
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.
Data Design and Implementation. Definitions Atomic or primitive type A data type whose elements are single, non-decomposable data items Composite type.
List Interface and Linked List Mrs. Furman March 25, 2010.
Iterators ITI 1121 N. El Kadri. Motivation Given a (singly) linked-list implementation of the interface List, defined as follows, public interface List.
Chapter 5 Array-Based Structures © 2006 Pearson Education Inc., Upper Saddle River, NJ. All rights reserved.
Arrays and ArrayLists Topic 6. One Dimensional Arrays Homogeneous – all of the same type Contiguous – all elements are stored sequentially in memory For.
Lecture 7 February 24, Javadoc version and author Tags These go in the comments before named classes. –Put your SS# on a separate line from the.
CSE 143 Lecture 4 More ArrayIntList : Pre/postconditions; exceptions; testing reading: slides created by Marty Stepp and Hélène Martin
Lecture 8: Advanced OOP Part 2. Overview Review of Subtypes Interfaces Packages Sorting.
IMPLEMENTING ARRAYLIST COMP 103. RECAP  Comparator and Comparable  Brief look at Exceptions TODAY  Abstract Classes - but note that the details are.
Topic 13 Iterators. 9-2 Motivation We often want to access every item in a data structure or collection in turn We call this traversing or iterating over.
CSE 501N Fall ‘09 10: Introduction to Collections and Linked Lists 29 September 2009 Nick Leidenfrost.
M180: Data Structures & Algorithms in Java Stacks Arab Open University 1.
1 Chapter 4 Unordered List. 2 Learning Objectives ● Describe the properties of an unordered list. ● Study sequential search and analyze its worst- case.
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,
(c) University of Washington20c-1 CSC 143 Binary Search Trees.
CSE 143 Lecture 3 Implementing ArrayIntList reading: slides created by Marty Stepp and Hélène Martin
1 Stacks Abstract Data Types (ADTs) Stacks Application to the analysis of a time series Java implementation of a stack Interfaces and exceptions.
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
An Array-Based Implementation of the ADT List
EECE 310: Software Engineering
Prof. Neary Adapted from slides by Dr. Katherine Gibson
Programming in Java Lecture 11: ArrayList
CSE 143 Lecture 27: Advanced List Implementation
ArrayLists 22-Feb-19.
List Implementation via Arrays
CSC 143 Java Linked Lists.
CSC 143 Binary Search Trees.
slides created by Ethan Apter and Marty Stepp
Presentation transcript:

(c) University of Washington15-1 CSC 143 Java List Implementation via Arrays Reading: 13

(c) University of Washington15-2 Implementing a List in Java Two implementation approaches are most commonly used for simple lists: List via Arrays Linked list Java Interface List concrete classes ArrayList, LinkedList same methods, different internals List in turn extends (implements) Collection Our current activities: Lectures on list implementations, in gruesome detail SimpleArrayList is a class we develop as an example Projects in which lists are used

(c) University of Washington15-3 List Interface (review) int size( ) boolean isEmpty( ) boolean add( E o) boolean addAll( Collection other) // Not exactly the signature, but… void clear( ) E get(int pos) boolean set( int pos, E o) int indexOf( Object o) boolean contains( Object o) E remove( int pos) boolean remove( Object o) boolean add( int pos, E o) Iterator iterator( )

(c) University of Washington15-4 Just an Illusion? Key concept: external view (the abstraction visible to clients) vs. internal view (the implementation ) SimpleArrayList may present an illusion to its clients Appears to be a simple, unbounded list of elements Actually may be a complicated internal structure The programmer as illusionist... This is what abstraction is all about

(c) University of Washington15-5 Using an Array to Implement a List Idea: store the list elements in an array instance variable // Simple version of ArrayList for CSE143 lecture example public class SimpleArrayList implements List { /** variable to hold all elements of the list*/ private E[ ] elements; … } Issues: How big to make the array? Algorithms for adding and deleting elements (add and remove methods) Later: performance analysis of the algorithms elements Object[ ]

(c) University of Washington15-6 Space Management: Size vs. Capacity Idea: allocate extra space in the array, possibly more than is actually needed at a given time size : the number of elements in the list, from the client's view capacity : the length of the array (the maximum size) invariant: 0 <= size <= capacity When list object created, create an array of some initial maximum capacity What happens if we try to add more elements than the initial capacity? see later…

(c) University of Washington15-7 List Representation public class SimpleArrayList implements List { // instance variables private E[ ] elements;// elements stored in elements[0..numElems-1] private int numElems;// size: # of elements currently in the list // capacity ?? Why no capacity variable?? // default capacity private static final int DEFAULT_CAPACITY = 10; … } Review: what is the “static final”?

(c) University of Washington15-8 Constructors We’ll provide two constructors: /** Construct new list with specified capacity */ public SimpleArrayList( int capacity) { this.elements = (E[]) new Object[capacity]; // new E[capacity] doesn’t work! this.numElems = 0; } /** Construct new list with default capacity */ public SimpleArrayList( ) { this(DEFAULT_CAPACITY); } Review: this( … ) means what? can be used where?

(c) University of Washington15-9 size, isEmpty : Signatures size: /** Return size of this list */ public int size( ) { } isEmpty: /** Return whether the list is empty (has no elements) */ public boolean isEmpty( ) { }

(c) University of Washington15-10 size, isEmpty : Code size: /** Return size of this list */ public int size( ) { return this.numElems; } isEmpty: /** Return whether the list is empty (has no elements) */ public boolean isEmpty( ) { return this.size( ) == 0; //OR return this.numElems == 0; } Each choice has pros and cons: what are they?

(c) University of Washington15-11 Method add : simple version Assuming there is unused capacity … /** Add object o to the end of this true if the object was added successfully. This implementation always returns true. */ public boolean add(E o) { return true; } o

(c) University of Washington15-12 Method add : simple version Assuming there is unused capacity … /** Add object o to the end of this true, since list is always changed by an add */ public boolean add(E o) { if (this.numElems < this.elements.length) { this.elements[this.numElems] = o; this.numElems ++; } else { // yuck; what can we do here? here's a temporary measure…. throw new RuntimeException("list capacity exceeded"); } return true; } addAll(array or list) left as an exercise – try it at home! Could your solution be put in an abstract superclass?

(c) University of Washington15-13 Method clear : Signature /** Empty this list */ public void clear( ) { } Can be done by adding just one line of code! "Can be", but "should be"?

(c) University of Washington15-14 clear : Code Logically, all we need to do is set this.numElems = 0 But it’s good practice to null out all of the object references in the list. Why? /** Empty this list */ public void clear( ) { for ( int k = 0; k < this.numElems; k++) { //optional this.elements[k] = null; // triggers a garbage collection if it is the only // reference } // DON’T DO: for (Object o : elements) { o = null; } WHY? this.numElems = 0; }

(c) University of Washington15-15 Method get /** Return object at position pos of this list The list is unchanged */ public E get( int pos) { return this.elements[pos]; } Anything wrong with this? Hint: what are the preconditions?

(c) University of Washington15-16 A Better get Implementation We want to catch out-of-bounds arguments, including ones that reference unused parts of array elements /** Return object at position pos of this list. 0 <= pos < size( ), or IndexOutOfBoundsException is thrown */ public E get( int pos) { if (pos = this.numElems) { throw new IndexOutOfBoundsException( ); } return (E) this.elements[pos]; } Question: is a "throws" clause required? Exercise: write out the preconditions more fully Exercise: specify and implement the set method Exercise: rewrite the above with an assert statement

(c) University of Washington15-17 Method indexOf Sequential search for first “equal” object /** return first location of object o in this list if found, otherwise return –1 */ public int indexOf( Object o) { for ( int k = 0; k < this.size( ); k++) { E elem = this.get(k); if (elem.equals(o)) { // found item; return its position return k; } // item not found return -1; } Exercise: write postconditions Could this be implemented in an abstract superclass?

(c) University of Washington15-18 Method contains /** return true if this list contains object o, otherwise false */ public boolean contains( Object o) { // just use indexOf return this.indexOf(o) != -1; } As usual, an alternate, implementation-dependent version is possible Exercise: define "this list contains object o" more rigorously

(c) University of Washington15-19 remove(pos) : Specification /** Remove the object at position pos from this list. Return the removed element. 0 <= pos < size( ), or IndexOutOfBoundsException is thrown */ public E remove( int pos) {... return removedElem; } Postconditions: quite a bit more complicated this time... Try writing them out! Key observation for implementation: we need to compact the array after removing something in the middle; slide all later elements left one position pos

(c) University of Washington15-20 Array Before and After remove Before After – Wrong! After – Right! pos

(c) University of Washington15-21 remove(pos) : Code /** Remove the object at position pos from this list. Return the removed element. 0 <= pos < size( ), or IndexOutOfBoundsException is thrown */ public E remove( int pos) { if (pos = this.numElems) { throw new IndexOutOfBoundsException( ); } E removedElem = this.elements[pos]; for (int k = pos+1; k < this.numElems; k++) { this.elements[k-1] = this.elements[k];// slide k'th element left by one index } this.elements[this.numElems-1] = null;// erase extra ref. to last element, for GC this.numElems--; return removedElem; }

(c) University of Washington15-22 remove (Object) /** Remove the first occurrence of object o from this list, if true if list altered, false if not */ public boolean remove(Object o) { int pos = indexOf(o); if (pos != -1) { remove(pos); return true; } else { return false; } Pre- and postconditions are not quite the same as remove(pos)

(c) University of Washington15-23 add Object at position /** Add object o at position pos in this list. List changes, so return true 0 <= pos < size( ), or IndexOutOfBoundsException is thrown */ public boolean add( int pos, E o) { … Key implementation idea: we need to make space in the middle; slide all later elements right one position Pre- and postconditions? pos

(c) University of Washington15-24 add(pos, o) : Code /** Add object o at position pos in this list. List changes, so return true 0 <= pos < size( ), or IndexOutOfBoundsException is thrown */ public boolean add( int pos, E o) { if (pos = this.numElems) { throw new IndexOutOfBoundsException( ); } if (this.numElems >= this.elements.length) { // yuck; what can we do here? here's a temporary measure…. throw new RuntimeException("list capacity exceeded"); } … continued on next slide …

(c) University of Washington15-25 add(pos, o) (continued) … //preconditions have been met // first create a space for ( int k = this.numElems - 1; k >= pos; k --) { // must count down! this.elements[k+1] = this.elements[k]; // slide k'th element right by one index } this.numElems ++; // now store object in the space opened up this.elements[pos] = o;// erase extra ref. to last element, for GC return true; }

(c) University of Washington15-26 add Revisited – Dynamic Allocation Our original version of add checked for the case when adding an object to a list with no spare capacity But did not handle it gracefully: threw an exception Better handling: "grow" the array Problem: Java arrays are fixed size – can't grow or shrink Solution: Make a new array of needed size This is called dynamic allocation

(c) University of Washington15-27 Dynamic Allocation Algorithm Algorithm: 1.allocate a new array with larger capacity, 2.copy the elements from the old array to the new array, and 3.replace the old array with the new one i.e., make the array name refer to the new array Issue: How big should the new array be?

(c) University of Washington15-28 Method add with Dynamic Allocation Following implementation has the dynamic allocation buried out of sight... /** Add object o to the end of this true, since list is always changed by an add */ public boolean add( E o) { this.ensureExtraCapacity(1); this.elements[this.numElems] = o; this.numElems ++; return true; } /** Ensure that elements has at least extraCapacity free space, growing elements if needed */ private void ensureExtraCapacity( int extraCapacity) { … magic here … }

(c) University of Washington15-29 ensureExtraCapacity /** Ensure that elements[] has at least extraCapacity free space, growing elements[] if needed */ private void ensureExtraCapacity( int extraCapacity) { if (this.numElems + extraCapacity > this.elements.length) { // we need to grow the array int newCapacity = this.elements.length * 2 + extraCapacity; E[] newElements = (E[]) new Object[newCapacity]; for ( int k = 0; k < this.numElems; k++) { newElements[k] = this.elements[k]; //copying old to new } this.elements = newElements; } Note: this is ensure extra capacity, not add extra capacity (there is an if statement). Pre- and Post- conditions? Check the method System.arraycopy

(c) University of Washington15-30 Method iterator Collection interface specifies a method iterator( ) that returns a suitable Iterator for objects of that class Key Iterator methods: boolean hasNext( ), E next( ) Method remove( ) is optional for Iterator in general, but expected to be implemented for lists. [left as an exercise] Idea: Iterator object holds... a reference to the list it is traversing and the current position in that list. Can be used for any List, not just ArrayList! Except for remove( ), iterator operations should never modify the underlying list

(c) University of Washington15-31 Method iterator In class SimpleArrayList /** Return a suitable iterator for this list */ public Iterator iterator ( ) { return new SimpleListIterator(this); }

(c) University of Washington15-32 Class SimpleListIterator (1) /** Iterator helper class for lists */ class SimpleListIterator implements Iterator { // instance variables private List list;// the list we are traversing private int nextItemPos;// position of next element to visit (if any left) // invariant: 0 <= nextItemPos <= list.size( ) /** construct iterator object */ public SimpleListIterator(List list) { this.list = list; this.nextItemPos = 0; } …

(c) University of Washington15-33 Class SimpleListIterator (2) /** return true if more objects remain in this iteration */ public boolean hasNext( ) { return this.nextItemPos < this.list.size( ); } /** return next item in this iteration and advance. Note: changes the state of the Iterator but not of the NoSuchElementException if iteration has no more elements */ public E next( ) { if ( ! hasNext( ) ) { throw new NoSuchElementException( ); } E result = this.list.get(this.nextItemPos); this.nextItemPos ++; return result; }

(c) University of Washington15-34 Design Question Why create a separate Iterator object? Couldn't the list itself have.....operations for iteration? hasNext( ) next( ) reset( ) //start iterating again from the beginning

(c) University of Washington15-35 Summary SimpleArrayList presents an illusion to its clients Appears to be a simple, unbounded list of elements Actually a more complicated array-based implementation Key implementation ideas: capacity vs. size/numElems sliding elements to implement (inserting) add and remove growing to increase capacity when needed growing is transparent to client Caution: Frequent sliding and growing is likely to be expensive….