IMPLEMENTING ARRAYLIST – Part 2 COMP 103. RECAP  Abstract Classes – overview, details in 2 nd year  Implementing the ArrayList: size(), get(), set()

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.
Lists and the Collection Interface Chapter 4. Chapter Objectives To become familiar with the List interface To understand how to write an array-based.
The List ADT Textbook Sections
Arrays and ArrayLists Ananda Gunawardena. Introduction Array is a useful and powerful aggregate data structure presence in modern programming languages.
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.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 10 Using arrays to create collections.
Bag implementation Add(T item) – Enlarge bag if necessary; allocate larger array Remove(T item) – Reduce bag if necessary; allocate smaller array Iterator.
Lists and Iterators (Chapter 6) COMP53 Oct 22, 2007.
Lists and the Collection Interface Chapter 4. Chapter 4: Lists and the Collection Interface2 Chapter Objectives To become familiar with the List interface.
Chapter 14 Generics and the ArrayList Class Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Fall 2007CS 2251 Lists and the Collection Interface Chapter 4.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 10 Using arrays to create collections.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 10 Using arrays to create collections.
Stacks, Queues, and Deques
COMP 103 Iterators and Iterable. RECAP  Maps and Queues TODAY  Queue Methods  Iterator and Iterable 2 RECAP-TODAY.
Arrays And ArrayLists - S. Kelly-Bootle
Introduction to Analysing Costs 2015-T2 Lecture 10 School of Engineering and Computer Science, Victoria University of Wellington  Marcus Frean, Rashina.
Lists Ellen Walker CPSC 201 Data Structures Hiram College.
Analysing Costs: ArraySet Binary Search COMP 103.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington ArraySet and Binary Search.
© 2004 Goodrich, Tamassia Stacks. © 2004 Goodrich, Tamassia Stacks2 Abstract Data Types (ADTs) An abstract data type (ADT) is an abstraction of a data.
COMP 103 Linked Lists. 2 RECAP-TODAY RECAP  Linked Structures: LinkedNode  Iterating and printing Linked Nodes  Inserting and removing Linked Nodes.
30 May Stacks (5.1) CSE 2011 Winter Stacks2 Abstract Data Types (ADTs) An abstract data type (ADT) is an abstraction of a data structure An.
1/20/03A2-1 CS494 Interfaces and Collection in Java.
Information and Computer Sciences University of Hawaii, Manoa
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.
2014-T2 Lecture 19 School of Engineering and Computer Science, Victoria University of Wellington  Marcus Frean, Lindsay Groves, Peter Andreae, and John.
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures for Java William H. Ford William R. Topp Chapter 13 Implementing.
2013-T2 Lecture 18 School of Engineering and Computer Science, Victoria University of Wellington  Marcus Frean, Lindsay Groves, Peter Andreae, and John.
More about costs: cost of “ensureCapacity”, cost of ArraySet, Binary Search 2014-T2 Lecture 12 School of Engineering and Computer Science, Victoria University.
(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.
CS 367 Introduction to Data Structures Lecture 2 Audio for Lecture 1 is available Homework 1 due Friday, September 18.
Copyright © 0 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java From Control Structures through Data Structures by Tony.
ANALYSING COSTS COMP 103. RECAP  ArrayList: add(), ensuring capacity, iterator for ArrayList TODAY  Analysing Costs 2 RECAP-TODAY.
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.
Iterators, Iterator, and Iterable 2015-T2 Lecture 8 School of Engineering and Computer Science, Victoria University of Wellington COMP 103 Thomas Kuehne.
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.
Iteration Abstraction SWE Software Construction Fall 2009.
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.
2015-T2 Lecture 19 School of Engineering and Computer Science, Victoria University of Wellington  Marcus Frean, Lindsay Groves, Peter Andreae, and John.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington2012 Analysing Costs COMP 103.
1 Example: LinkedStack LinkedStack UML Class Diagram LinkedStack Class LinkedStack Attributes/Constructor LinkedStack Methods LinkedStack iterator method.
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,
Recursive Objects Singly Linked List (Part 2) 1. Operations at the head of the list  operations at the head of the list require special handling because.
Testing with JUnit, Introduction to Analysing Costs 2013-T2 Lecture 10 School of Engineering and Computer Science, Victoria University of Wellington 
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java From Control Structures through Data Structures by.
Introduction to Analysing Costs 2013-T2 Lecture 10 School of Engineering and Computer Science, Victoria University of Wellington  Marcus Frean, Rashina.
Iterators. Iterator  An iterator is any object that allows one to step through each element in a list (or, more generally, some collection).
An Array-Based Implementation of the ADT List
Introduction to Analysing Costs
Implementing ArrayList Part 1
Programming in Java Lecture 11: ArrayList
Data Type (how to view it)
(Java Collections Framework) AbstractSequentialList
Arrays versus ArrayList
Example: LinkedSet<T>
The Vector Class An object of class Vector is similar to an array in that it stores multiple values However, a vector only stores objects does not have.
ArrayLists 22-Feb-19.
Programming II (CS300) Chapter 02: Using Objects Java ArrayList Class
List Implementation via Arrays
CSC 143 Java Linked Lists.
Presentation transcript:

IMPLEMENTING ARRAYLIST – Part 2 COMP 103

RECAP  Abstract Classes – overview, details in 2 nd year  Implementing the ArrayList: size(), get(), set() and remove() TODAY  ArrayList: add(), ensuring capacity, iterator for ArrayList 2 RECAP-TODAY

ArrayList: add (pseudocode) public class ArrayList extends AbstractList { private E[] data; private int count=0; : /** Adds the specified element at the specified index */ public void add(int index, E item){ // check that the index is within the allowed bounds // above the index, move the items up, starting at the last // insert the item into the gap // increment the ‘count’ variable } 9 3

ArrayList: add public class ArrayList extends AbstractList { private E[] data; private int count=0; : /** Adds the specified element at the specified index */ public void add(int index, E item){ if (index = count) ←check sensible throw new IndexOutOfBoundsException(); for (int i=count; i > index; i--) ←move items up data[i]=data[i-1]; data[index]=item; ←insert count++; ←increment }  What’s wrong ??? (two things) 9 4

ArrayList: add (fixed) public class ArrayList extends AbstractList { private E[] data; private int count=0; : /** Adds the specified element at the specified index.*/ public void add(int index, E item){ if (index count) ←can add at end! throw new IndexOutOfBoundsException(); ensureCapacity();←make room for (int i=count; i > index; i--) data[i]=data[i-1]; data[index]=item; count++; } 9 5

Increasing Capacity  three steps: 8 data count newArray data.length = 8 6 ArrayList

ArrayList: ensureCapacity /**Ensure data array has sufficient number of elements * to add a new element */ private void ensureCapacity () { if (count < data.length) return; ← there is room already E [ ] newArray = (E[ ]) (new Object[data.length + …....] ); for (int i = 0; i < count; i++) ← copy to the new array newArray[i] = data[i]; data = newArray; ← replace old array with new one } 7 1 ? INITIALCAPACITY ? data.length ? How much bigger should this new array be?

ArrayList: What else ?  iterator():  defining an iterator for ArrayList.  Cost:  What is the cost (time) of adding or removing an item ?  How expensive is it to increase the size ?  How should we increase the size ? 8

An iterator for ArrayList 9 List toDoList = new ArrayList (); iter toDoList Iterator iter = toDoList.iterator(); Conforms to the interface Iterator so… has these methods: hasNext() next() remove() Conforms to the interface List so… has these methods: add() remove() contains(), iterator(), etc… etc...

Iterator 10 list nextIndex 0 9 ArrayList: Iterator:

ArrayList: iterator 11 /** Returns an iterator over the elements in the List */ public Iterator iterator() { return new ArrayListIterator (this); } /** Definition of the iterator for an ArrayList */ private class ArrayListIterator implements Iterator { // fields to store state // constructor // hasNext(), // next(), // remove() } Technical point: - in general, an iterator will need to know the object it is attached to. But in our case it isn’t strictly necessary to pass it in (as “this”), because we’re going to put the iterator in as a “private inner class” of ArrayList.

ArrayList iterator 12 private class ArrayListIterator implements Iterator { private ArrayList list; // reference to the list object private int nextIndex; // the index of the next value to return private boolean canRemove = false; // to allow the “remove” operation /** Constructor */ private ArrayListIterator (ArrayList list) { this.list = list; nextIndex = 0; } /** Return true if the array has at least one more element */ public boolean hasNext () { return (nextIndex < list.count); }

Iterator: next, remove (simple version) 13 /** Return next element in the List */ public E next () { if (nextIndex >= list.count) throw new NoSuchElementException(); E temp = list.get(nextIndex); nextIndex++; return temp; ← increment and return } /** Should remove from the list the last element that was returned by the iterator. */ public void remove(){ throw new UnsupportedOperationException(); } Notice: this means “remove()” should only be called once, per call to “next()” !

Example list nextIndex 5 canRemove true

Iterator: next, remove (smarter version) 15 /** Return next element in the List */ public E next () { if (nextIndex >= list.count) throw new NoSuchElementException(); canRemove = true; ← for the remove method E temp = list.get(nextIndex); nextIndex++; return temp; } /** Remove from the list the last element returned by the iterator. * Can only be called once per call to next. */ public void remove(){ if ( ! canRemove ) throw new IllegalStateException(); canRemove = false;← can only remove once nextIndex--; ← put counter back to last item list.remove(nextIndex); ← remove last item }

Multiple Iterators 16 list nextIndex 3 canRemove true list nextIndex 5 canRemove true

Iterator: Summary  Each iterator keeps track of its own position in the List  Removing the last item returned is possible, but… ...The implementation is not smart, and may be corrupted if any changes are made to the ArrayList that it is iterating down.  How to modify this to use something other than a boolean field to make it possible to work more generally? (Hint: java.util.ArrayList uses a counter!)  Note that because it is an inner class, it has access to the ArrayList's private fields. 17

Analysing Costs (in general) How can we determine the costs of a program?  Time:  Run the program and count the milliseconds/minutes/days.  Count number of steps/operations the algorithm will take.  Space:  Measure the amount of memory the program occupies.  Count the number of elementary data items the algorithm stores.  Programs or Algorithms?  Both programs: benchmarking algorithms: analysis 18

ArrayList: Cost  What’s the cost of contains, get, set, remove, add…?  How should we implement ensureCapacity() ?  How do you measure cost of operations on collections?  What is “cost” of an algorithm?  Number of steps required if the list contains n items:  get:  set:  remove:  add: 19