CS 310: ArrayList Implementation

Similar documents
CS 310: Array- and Linked-based Data Structures

CS 211: Using ArrayList, Implementing Arraylist

CS 211: Using ArrayList, Implementing Arraylist

CS 310: Linked Queues and Array Queues

Outline. runtime of programs algorithm efficiency Big-O notation List interface Array lists

CSCI 1103: Array-based Data Structures

CS 310: Array-y vs Linky Lists

CS 310: HW 1, Junit, Generics Review

The list abstract data type defined a number of operations that all list-like objects ought to implement:

Lecture 6: ArrayList Implementation

CSE 331. Generics (Parametric Polymorphism)

CS 222: Arrays, Strings, Structs

Last Week: Organizing Data. Last Week: Parallel Arrays. University of British Columbia CPSC 111, Intro to Computation Alan J. Hu.

Implementing a List in Java. CSE 143 Java. Just an Illusion? List Interface (review) Using an Array to Implement a List.

CS 310: Order Notation (aka Big-O and friends)

STUDENT LESSON A15 ArrayList

Implementing a List in Java. CSE 143 Java. List Interface (review) Just an Illusion? Using an Array to Implement a List.

Algorithms. Algorithms 1.3 STACKS AND QUEUES. stacks resizing arrays queues generics iterators applications ROBERT SEDGEWICK KEVIN WAYNE.

Test Class A. public class A { private int x, y; public int getx() { return x; } public int gety() { return y; }

Programming Abstractions

CS 310: Maps and Sets

Introduction to Object-Oriented Programming

CSE 331 Software Design and Implementation. Lecture 14 Generics 2

DM550 / DM857 Introduction to Programming. Peter Schneider-Kamp

Garbage Collection (1)

What are Generics? e.g. Generics, Generic Programming, Generic Types, Generic Methods

COMP200 GENERICS. OOP using Java, from slides by Shayan Javed

Algorithm Efficiency and Big-O

INTRODUCTION TO DATA AND PROCEDURE

CS 151. Exceptions & Javadoc. slides available on course website. Sunday, September 9, 12

CSE 331 Software Design and Implementation. Lecture 14 Generics 2

CS231 - Spring 2017 Linked Lists. ArrayList is an implementation of List based on arrays. LinkedList is an implementation of List based on nodes.

CSC 321: Data Structures. Fall 2013

Arrays.

CS 310: HW 1: DynamicArray

Arrays and ArrayLists. David Greenstein Monta Vista High School

Recursion (Part 3) 1

Advances in Programming Languages: Type accuracy

COMP-202 Unit 7: More Advanced OOP. CONTENTS: ArrayList HashSet (Optional) HashMap (Optional)

DM503 Programming B. Peter Schneider-Kamp.

CS 307 Midterm 2 Fall 2008

CS 310: Hash Table Collision Resolution Strategies

ITI Introduction to Computing II

Arrays and ArrayLists. Ananda Gunawardena

ITI Introduction to Computing II

Introduction. Introduction: Multi-Pop Stack Example. Multi-Pop Stack Cost (clever) Multi-Pop Stack Cost (naïve)

Today we begin studying how to calculate the total time of a sequence of operations as a whole. (As opposed to each operation individually.

CS 310: Hash Table Collision Resolution

CSC 321: Data Structures. Fall 2012

Interfaces, collections and comparisons

CS 310: Hash Table Collision Resolution

Week 4, Wednesday (Spring 2015). Dr. Yoder. Sec 051. Page 1 of 5

CSE 143 Lecture 26. Advanced collection classes. (ADTs; abstract classes; inner classes; generics; iterators) read 11.1, 9.6, ,

CSE 1223: Introduction to Computer Programming in Java Chapter 6 ArrayLists

CS 211: Potpourri Enums, Packages, Unit Tests, Multi-dimensional Arrays Command Line Args

CS 520 Theory and Practice of Software Engineering Fall 2018

CSCI 104. Rafael Ferreira da Silva. Slides adapted from: Mark Redekopp and David Kempe

List ADT. Announcements. The List interface. Implementing the List ADT

CS61B Lecture #23. Today: Java support for generic programming. Readings for today: A Java Reference, Chapter 10.

11-1. Collections. CSE 143 Java. Java 2 Collection Interfaces. Goals for Next Several Lectures

Review: List Implementations. CSE 143 Java. Links. A Different Strategy: Lists via Links. Linked Links. CSE143 Au List

Big O & ArrayList Fall 2018 Margaret Reid-Miller

Computer Science II (Spring )

CS 211: Inheritance. Chris Kauffman. Week 5-2

CS201 ArrayLists, Generics, and Dynamic Data Structures (Chapters 14, 15)

Lesson 2.4 Arraylist

CS 177 Recitation. Week 1 Intro to Java

CS 211: Recursion. Chris Kauffman. Week 13-1

CS 310: Priority Queues and Binary Heaps

Linked List. ape hen dog cat fox. tail. head. count 5

Arrays. Array Definition

COMP-202. Generics. COMP Generics, 2013 Jörg Kienzle and others

Le L c e t c ur u e e 8 To T p o i p c i s c t o o b e b e co c v o e v r e ed e Collections

Use of the ArrayList class

CS 310: Maps and Sets and Trees

Data Structures Brett Bernstein. Lecture 1: Introduction and a Review/Enrichment of CS 101

CP222 Computer Science II. Linked Lists

CS 310: Priority Queues and Binary Heaps

January 24, Abstract Data Types (ADTs) An ADT is an abstraction of a data structure.

CS 106B Practice Final Exam #8 (15au) ANSWER KEY

CS 307 Midterm 2 Spring 2011

CS 211: Methods, Memory, Equality

CS : Data Structures Michael Schatz. Oct 22, 2018 Lecture 22. Ordered Sets

CS 222: Linked Lists, Queues, Stacks

CS 520 Theory and Practice of Software Engineering Fall 2017

Slides are adapted from the originals available at

CS 520 Theory and Practice of Software Engineering Fall 2017

Generics, Type Safety, and Dynamic Data Structures

CS 222: Pointers and Manual Memory Management

Object Oriented Programming and Design in Java. Session 2 Instructor: Bert Huang

CSE 413 Languages & Implementation. Hal Perkins Winter 2019 Structs, Implementing Languages (credits: Dan Grossman, CSE 341)

Arrays. myints = new int[15];

CS 310: Hashing Basics and Hash Functions

Rules and syntax for inheritance. The boring stuff

CS61B Lecture #24. Today: Java support for generic programming. Readings for today: A Java Reference, Chapter 10.

CS 237 Meeting 19 10/24/12

Data & Procedure Introduction

CSCI 1103: Input with TextIO

CSE 373: AVL trees. Michael Lee Friday, Jan 19, 2018

Announcements. Lecture 15 Generics 2. Announcements. Big picture. CSE 331 Software Design and Implementation

Transcription:

CS 310: ArrayList Implementation Chris Kauffman Week 2-2

Logistics At Home Read Weiss Ch 5: Big-O Read Weiss Ch 15: ArrayList implementation Reminder to DrJava Users Consider Using GMU Edition of DrJava Download here: https://cs.gmu.edu/~kauffman/drjava/ Goals Build an array list Analyze its complexity

Collections Java has a nice library of containers, Collections framework Interfaces that provide get(), set(), add() All have parameterized types: ArrayList<E>, TreeSet<E> At present, most interested in ArrayList Like arrays but lacking nice [ ] syntax Use get() and set() instead Can add() elements at end (high index) Demonstrate ArrayList in DrJava

Basic Premise of the Expandable Array Use an underlying array public class MyArrayList<T>{ // This almost works T data[];... data is a standard fixed size array get()/set() are array ops Adding and Expanding Add elements into data If/when data runs out of space 1. Allocate a new larger array data2 2. Copy elements from data to data2 3. Add new element(s) to data2 4. Set data to data2 5. Original array gets garbage collected Questions What s the notion of size now? How much should the array grow on expansion? Is there wasted space? How much?

Create MyArrayList public class MyArrayList<T>{ T data[]; int size; // Holds elements, virtual size public MyArrayList(); // Initialize fields public int size(); // Virtual size of AL public void add(t x); // Add an element to the end public T get(int i); // Retrieve element i public void set(int i, T x); // Replace element i with x public void insert(int i, T x); // Insert x at position i, shift // elements if necessary public void remove(int i); // Remove element at position i, // shift elements to remove gap add(x) If/when data runs out of space 1. Allocate a new larger array data2 2. Copy from data to data2 3. Add new element(s) to data2 4. Set data to data2 5. GC gets the old array Respect My size() get()/set()/insert()/remove() must respect size() which is always smaller than or equal to data.length; check for out of bounds access

Examine Results Code up versions together quickly Simple version: MyArrayList.java in code distrib Also included java.util.arraylist from Java 1.7 source May also want to look at Weiss s version in textbook-source/weiss/util/arraylist.java Complexity What are the complexities for methods like set(i,x) and get(i) insert(i,x) and remove(i,x) add(x) : this is the big one

Limits of Types Unfortunately, java type system has some limits. new T[10] Not Allowed public class MyArrayList<T> { private T [] data; public MyArrayList(){ this.data=new T[10]; // Grrrr public T get(int i){ this.rangecheck(i); return this.data[i]; Instead: Object[] + Caste public class MyArrayList<T> { private T data[]; public MyArrayList(){ this.data=(t[]) new Object[10]; public T get(int i){ this.rangecheck(i); return this.data[i];

Unsafe Operations in MyArrayList lila [w01-2-1-code]% javac MyArrayList.java Note: MyArrayList.java uses unchecked or unsafe operations. Note: Recompile with -Xlint:unchecked for details. lila [w01-2-1-code]% javac -Xlint:unchecked MyArrayList.java MyArrayList.java:77: warning: [unchecked] unchecked cast found : java.lang.object[] required: T[] this.data = (T[]) new Object[10]; ^ 1 warning

Unsafe Operations Suppress Warnings Offending code is private T [] data; public MyArrayList(){ this.data=(t[]) new Object[10]; It is unsafe, but so is fire. Tell the compiler to shut up // I know what I m doing @SuppressWarnings("unchecked") public MyArrayList(){ this.data=(t[]) new Object[10]; Alternative: This version uses casting in get() public class MyArrayList<T> { Object [] data; public MyArrayList(){ this.data =new Object[10]; @SuppressWarnings("unchecked") public T get(int i){ this.rangecheck(i); return (T) this.data[i]; Also needed anywhere else type T stuff is returned so less preferred: more @SuppressWarnings

HW and Unsafe Operations Proper use of generics creates good compile-time type checking Rarely is casting required; ArrayList implementation is one such exception HW1 is NOT such a case Should not need to caste anything Should not need to use @SuppressWarnings Doing either may result in penalties

Warmup: Finish methods for MyArrayList public class MyArrayList<T>{ T data[]; int size; public MyArrayList(); public int size(); public T get(int i); public void add(t x); // Holds elements, virtual size // Initialize fields // Virtual size of AL // Retrieve element i // Add an element to the end // FINISH THESE public void set(int i, T x); // Replace element i with x public void insert(int i, T x); // Insert x at position i, shift // elements if necessary public void remove(int i); // Remove element at position i, // shift elements to remove gap Three methods of MyArrayList remain - finish them Note common patterns that should be factored into helpers (e.g. expansion, bounds checking) Note: al.insert(i,x) is called al.add(i,x) in java.util.arraylist

Exercise: ArrayList Complexities ArrayList of with N elements Time/Space Complexities of methods Worst-case or Average/Amoritzied Worst Average Worst Average Operation Method Runtime Runtime Space Space Size() al.size() Get(i) al.get(i) Set(i,x) al.set(i,x) Add(x) al.add(x) Insert(i,x) al.add(i,x) Remove(i) al.remove(i) What is the space complexity of an ArrayList with N elements? Is that a tight bound?

Expanding with Magic Numbers Size increase when expansion is required is interesting Can t be constant: increase size by 1, or 2, or 10 will not give good complexity Standard Java ArrayList increases to 3/2*oldSize+1 Chosen based on engineering experience rather than theory, can use bit shifts to compute it fast Default ArrayList size is 10 Magic Numbers: 3/2 and 10, magic because there is no good reason for them

Average/Amortized Complexity Worst case complexity for arraylist.add(x) is O(N) when expansion is required But expansion happens rarely if size increase by 150% during expansion Over many add operations, the average add(x) takes O(1) time complexity Amortized Analysis: sort of like average case (definition is close enough for this class)