Implementing ArrayList Part 1

Slides:



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

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.
CS 106 Introduction to Computer Science I 04 / 27 / 2007 Instructor: Michael Eckmann.
Java Collections Framework COMP53 Oct 24, Collections Framework A unified architecture for representing and manipulating collections Allows collections.
CS 106 Introduction to Computer Science I 05 / 03 / 2010 Instructor: Michael Eckmann.
15-Jun-15 Lists in Java Part of the Collections Framework.
24-Jun-15 Introduction to Collections. 2 Collections A collection is a structured group of objects Java 1.2 introduced the Collections Framework Collections.
Lists in Java Part of the Collections Framework. Kinds of Collections Collection --a group of objects, called elements –Set-- An unordered collection.
12-Jul-15 Lists in Java Part of the Collections Framework.
CS 106 Introduction to Computer Science I 04 / 30 / 2010 Instructor: Michael Eckmann.
1 Collection, Iterable, and Iterator Interfaces The Collection Interface and its Hierarchy The Iterable and Iterator Interfaces For-each Loops with Iterable.
Introduction to Analysing Costs 2015-T2 Lecture 10 School of Engineering and Computer Science, Victoria University of Wellington  Marcus Frean, Rashina.
Collections in Java. Kinds of Collections Collection --a group of objects, called elements –Set-- An unordered collection with no duplicates SortedSet.
JAVA COLLECTIONS LIBRARY School of Engineering and Computer Science, Victoria University of Wellington COMP T2, Lecture 2 Marcus Frean.
Generalized Containers CSIS 3701: Advanced Object Oriented Programming.
IMPLEMENTING ARRAYLIST – Part 2 COMP 103. RECAP  Abstract Classes – overview, details in 2 nd year  Implementing the ArrayList: size(), get(), set()
Peter Andreae Engineering and Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington2012 Implementing.
Data Design and Implementation. Definitions of Java TYPES Atomic or primitive type A data type whose elements are single, non-decomposable data items.
1/20/03A2-1 CS494 Interfaces and Collection in Java.
Collections in Java. 2 Collections Hierarchy > ArrayListVector Stack LinkedList > Arrays Collections.
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.
1 Collection, Iterable, and Iterator Interfaces The Collection Interface and its Hierarchy The Iterable and Iterator Interfaces For-each Loops with Iterable.
2013-T2 Lecture 18 School of Engineering and Computer Science, Victoria University of Wellington  Marcus Frean, Lindsay Groves, Peter Andreae, and John.
Interfaces, Classes, Collections School of Engineering and Computer Science, Victoria University of Wellington COMP T2 Lecture 3 Thomas Kuehne.
(c) University of Washington16-1 CSC 143 Java Lists via Links Reading: Ch. 23.
1 CMPSCI 187 Computer Science 187 Introduction to Introduction to Programming with Data Structures Lecture 8 Lists, Iterators, and Doubly Linked Lists.
JAVA COLLECTIONS LIBRARY School of Engineering and Computer Science, Victoria University of Wellington COMP T2, Lecture 2 Thomas Kuehne.
ANALYSING COSTS COMP 103. RECAP  ArrayList: add(), ensuring capacity, iterator for ArrayList TODAY  Analysing Costs 2 RECAP-TODAY.
Iterators, Iterator, and Iterable 2015-T2 Lecture 8 School of Engineering and Computer Science, Victoria University of Wellington COMP 103 Thomas Kuehne.
IMPLEMENTING ARRAYLIST COMP 103. RECAP  Comparator and Comparable  Brief look at Exceptions TODAY  Abstract Classes - but note that the details are.
List data type(ADT). Lists Elements : a 1,a 2,a 3,… a i-1,a i, a i+1,…a n Null List contains: 0 elements Types of Operations on list 1.Insertion 2.Deletion.
Interfaces, Classes, Collections School of Engineering and Computer Science, Victoria University of Wellington COMP T2 Lecture 3 Marcus Frean.
JAVA COLLECTIONS LIBRARY School of Engineering and Computer Science, Victoria University of Wellington COMP T2, Lecture 2 Marcus Frean.
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.
Object Oriented Programming in Java Habib Rostami Lecture 7.
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.
Introduction to Analysing Costs 2013-T2 Lecture 10 School of Engineering and Computer Science, Victoria University of Wellington  Marcus Frean, Rashina.
 2016, Marcus Biel, ArrayList Marcus Biel, Software Craftsman
1 CS162: Introduction to Computer Science II Abstract Data Types.
Interfaces, Classes, Collections School of Engineering and Computer Science, Victoria University of Wellington COMP T2 Lecture 3 Thomas Kuehne.
An Array-Based Implementation of the ADT List
Introduction to Analysing Costs
JAVA COLLECTIONS LIBRARY
JAVA COLLECTIONS LIBRARY
Data Structures Lakshmish Ramaswamy.
COP 3503 FALL 2012 Shayan Javed Lecture 8
TCSS 143, Autumn 2004 Lecture Notes
Programming in Java Lecture 11: ArrayList
Data Type (how to view it)
(Java Collections Framework) AbstractSequentialList
CSE 143 Lecture 27: Advanced List Implementation
Collections in Java The objectives of this lecture are:
Computer Science and Engineering
ArrayLists 22-Feb-19.
Collections Framework
Programming II (CS300) Chapter 02: Using Objects Java ArrayList Class
ArrayList.
Web Design & Development Lecture 6
TCSS 143, Autumn 2004 Lecture Notes
Part of the Collections Framework
Arrays and ArrayLists.
Java Generics & Iterators
Presentation transcript:

Implementing ArrayList Part 1 COMP 103 Implementing ArrayList Part 1 Thomas Kuehne, Marcus Frean, Rashina Hoda, and Peter Andreae Thomas Kuehne School of Engineering and Computer Science, Victoria University of Wellington 2016-T2 Lecture 6

RECAP-TODAY RECAP In the last lectures we looked at 2 RECAP In the last lectures we looked at Lists, Queues, Stacks Sets, Maps TODAY We will implement ArrayList from scratch to gain a deeper understanding of ArrayList make a first foray into complexity analysis learn how to implement a Java Collections Library interface

extends implements “extends” implies subtyping; instances of subtypes will behave like their supertypes expect them to “implements” signifies realisation; classes promise to fulfill the contracts defined by (interface) types

Inheritance ("extends") 4 public class Square extends Shape {...} public class Dictionary extends Book { ... } public interface List <E> extends Collection <E> { ... } Java uses the reserved word extends to indicate that a class or interface is being derived from an existing one. Extends establishes a subtype relationship. every Dictionary is a (behaves like a) Book every List is a (behaves like a) Collection To support this, all methods defined in the parent class (and all its variables, if any) are inherited. More on this in SWEN221…

Interfaces and Classes 5 Interface Specifies type (typically) defines method signatures only Class Implements interface defines variables for the data defines method bodies defines constructors List <E> Specifies sequence of E size, add, get, set, remove, addAll, clear, contains, containsAll, equals, hashCode, isEmpty, indexOf, lastIndexOf, iterator, listIterator, … ArrayList <E> implements List <E> defines array of <E> defines size, add, … defines constructors

Defining ArrayList Design the data structures to store the elements 6 Design the data structures to store the elements array of items count Define the fields and constructors public class ArrayList <E> implements List<E> { private E [ ] data; private int count; … Define all the methods specified in the List interface: size() add(E o) add(int index, E element) contains(Object o) get(int index) isEmpty() clear() set(int index, E element) indexOf(Object o) remove(int index) remove(Object o) lastIndexOf(Object o) iterator() equals(Object o) hashCode() listIterator() listIterator(int index) …

Implementing ArrayList 7 Data structure: data count size() returns the value of count get(index) and set(index, elem) check if index is within bounds, and access/set the appropriate slot in the array add (index, elem) check if index is within bounds, (0..size) (move other items up, and) insert element ensure further capacity if the currently used array becomes too small

ArrayList: fields and constructor 8 public class ArrayList <E> implements List <E> { private E[ ] data; private int count=0; private static final int INITIALCAPACITY = 16; . We could do this, but it would imply a lot of work!

ArrayList: fields and constructor 9 public class ArrayList <E> extends AbstractList <E> { private E[ ] data; private int count=0; private static final int INITIALCAPACITY = 16; public ArrayList() {     data = new E [INITIALCAPACITY];  } We cannot use type variables as array constructors! Have to create as Object[ ], and then cast to E[ ] Compiler will warn, but the warning is safe to ignore here may use “@SuppressWarnings("unchecked")” This saves us considerable effort and will be explained in the next lecture Cannot use “E[]” because of “type erasure”. (E[ ]) new Object[INITIALCAPACITY];

ArrayList: size(), isEmpty() 10 public class ArrayList <E> extends AbstractList <E> { private E[ ] data; private int count=0; : /** @return number of elements in collection as integer */   public int size () {     return count;   } /** @return true, if this set contains no elements. */   public boolean isEmpty() {     return count==0;   } 9

ArrayList: get(index) 11 public class ArrayList <E> extends AbstractList<E> { private E[ ] data; private int count=0; : /** @return the element at the specified index. * Throws an IndexOutOfBoundsException, if index is out of bounds*/   public E get(int index) {     if (index < 0 || index >= count) throw new IndexOutOfBoundsException();     return data[index];   }  9

ArrayList: set(index, element) 12 public class ArrayList <E> extends AbstractList<E> { private E[ ] data; private int count=0; : /** Replaces the element at the specified index by the specified element. * @return the old element. * Throws an IndexOutOfBoundsException, if index is out of bounds */ public E set(int index, E element) {     if (index < 0 || index >= count) throw new IndexOutOfBoundsException();     E oldElement = data[index];     data[index] = element;     return oldElement; } 9

ArrayList: remove(index) 13 public class ArrayList <E> extends AbstractList <E> { private E[] data; private int count=0; /** Removes the element at the specified index, and returns it. * Throws an IndexOutOfBoundsException if index is out of bounds */ public E remove (int index) {     if (index < 0 || index >= count) throw new IndexOutOfBoundsException();     E oldElement = data[index]; ← remember old element     for (int i=index; i < count-1; i++) ← move items down       data[i]=data[i+1];            count--; ← adjust size variable data[count] = null; ← delete reference     return oldElement; ( garbage collection) }   9 The last assignment in the for loop goes out of bounds It leaves a copy of the last item just beyond the end of the “real” items, which may prevent garbage collection.

ArrayList: add (pseudocode) 14 public class ArrayList <E> extends AbstractList <E> { 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  // adjust the size variable }   9 This won’t let you add an item at the end!! What happens if the array is full?

ArrayList: add What’s wrong??? (two issues) 15 public class ArrayList <E> extends AbstractList <E> { private E[] data; private int count=0; : // Adds the specified element at the specified index public void add(int index, E item) {   if (index < 0 || index count) throw new IndexOutOfBoundsException();   for (int i=count; i > index; i--) ← move items up     data[i] = data[i-1];   data[index] = item; ← insert element   count++; ← adjust size variable }   What’s wrong??? (two issues) 9 This won’t let you add an item at the end!! What happens if the array is full? >= > ← can add at end! ensureCapacity(); ← make room, if required

Ensuring Capacity Three steps: ArrayList data.length = 8 data count 16 newArray

ArrayList: ensureCapacity 17 /** * Ensures 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 } How much bigger should this new array be? One ? INITIALCAPACITY ? data.length ?