ArrayLists & List Computational Complexity

Similar documents
Data Structures and Algorithms

Estrutura com iterador-1

D06 PROGRAMMING with JAVA

API for java.util.iterator. ! hasnext() Are there more items in the list? ! next() Return the next item in the list.

Data Structures in the Java API

Data Structures and Algorithms Lists

Datastrukturer och standardalgoritmer i Java

Class 32: The Java Collections Framework

Java Collection Framework hierarchy. What is Data Structure? Chapter 20 Lists, Stacks, Queues, and Priority Queues

Collections in Java. Arrays. Iterators. Collections (also called containers) Has special language support. Iterator (i) Collection (i) Set (i),

Universidad Carlos III de Madrid

Masters programmes in Computer Science and Information Systems. Object-Oriented Design and Programming. Sample module entry test xxth December 2013

Software Engineering II. Java 2 Collections. Bartosz Walter <Bartek.Walter@man.poznan.pl>

CMSC 202H. ArrayList, Multidimensional Arrays

Software Development with UML and Java 2 SDJ I2, Spring 2010

Stacks and queues. Algorithms and Data Structures, Fall Rasmus Pagh. Based on slides by Kevin Wayne, Princeton

The Java Collections Framework

Cpt S 223. School of EECS, WSU

Generic Types in Java. Example. Another Example. Type Casting. An Aside: Autoboxing 4/16/2013 GENERIC TYPES AND THE JAVA COLLECTIONS FRAMEWORK.

Chapter 8: Bags and Sets

CompSci-61B, Data Structures Final Exam

Collections and iterators

1.00 Lecture 35. Data Structures: Introduction Stacks, Queues. Reading for next time: Big Java: Data Structures

A binary search tree or BST is a binary tree that is either empty or in which the data element of each node has a key, and:

Free Java textbook available online. Introduction to the Java programming language. Compilation. A simple java program

Free Java textbook available online. Introduction to the Java programming language. Compilation. A simple java program

Arrays. Atul Prakash Readings: Chapter 10, Downey Sun s Java tutorial on Arrays:

Queues Outline and Required Reading: Queues ( 4.2 except 4.2.4) COSC 2011, Fall 2003, Section A Instructor: N. Vlajic

LINKED DATA STRUCTURES

JAVA COLLECTIONS FRAMEWORK

Data Types. Abstract Data Types. ADTs as Design Tool. Abstract Data Types. Integer ADT. Principle of Abstraction

Sequential Data Structures

Simple sorting algorithms and their complexity. Bubble sort. Complexity of bubble sort. Complexity of bubble sort. Bubble sort of lists

STORM. Simulation TOol for Real-time Multiprocessor scheduling. Designer Guide V3.3.1 September 2009

Circular Linked List. Algorithms and Data Structures

Overview. Elements of Programming Languages. Advanced constructs. Motivating inner class example

Computer Programming I

What is a Stack? Stacks and Queues. Stack Abstract Data Type. Java Interface for Stack ADT. Array-based Implementation

DATA STRUCTURE - STACK

Working with Java Collections

The Interface Concept

22c:31 Algorithms. Ch3: Data Structures. Hantao Zhang Computer Science Department

CSE 2123 Collections: Sets and Iterators (Hash functions and Trees) Jeremy Morris

Java Interview Questions and Answers

Course: Programming II - Abstract Data Types. The ADT Stack. A stack. The ADT Stack and Recursion Slide Number 1

AP Computer Science Java Subset

This lecture. Abstract data types Stacks Queues. ADTs, Stacks, Queues Goodrich, Tamassia

Singly linked lists (continued...)

Algorithms and Data Structures Written Exam Proposed SOLUTION

Outline. Computer Science 331. Stack ADT. Definition of a Stack ADT. Stacks. Parenthesis Matching. Mike Jacobson

1. The memory address of the first element of an array is called A. floor address B. foundation addressc. first address D.

Software Engineering Techniques

Introduction to Object-Oriented Programming

AP Computer Science A Syllabus

Introduction to Programming System Design. CSCI 455x (4 Units)

STACKS,QUEUES, AND LINKED LISTS

Programming with Data Structures

Lecture J - Exceptions

Practical Session 4 Java Collections

Basic Programming and PC Skills: Basic Programming and PC Skills:

Last not not Last Last Next! Next! Line Line Forms Forms Here Here Last In, First Out Last In, First Out not Last Next! Call stack: Worst line ever!

Searching Algorithms

Java Map and Set collections

Sequences in the C++ STL

Introduction to Stacks

Java Application Developer Certificate Program Competencies

Analysis of a Search Algorithm

10 Java API, Exceptions, and Collections

Principles of Software Construction: Objects, Design and Concurrency. Java Collections. toad Fall 2013

Stacks. Stacks (and Queues) Stacks. q Stack: what is it? q ADT. q Applications. q Implementation(s) CSCU9A3 1

Chapter 3: Restricted Structures Page 1

Lecture 12: Abstract data types

COSC Introduction to Computer Science I Section A, Summer Question Out of Mark A Total 16. B-1 7 B-2 4 B-3 4 B-4 4 B Total 19

Introduction to Data Structures

C++ Overloading, Constructors, Assignment operator

Computing Concepts with Java Essentials

Iterators. Provides a way to access elements of an aggregate object sequentially without exposing its underlying representation.

COMPUTER SCIENCE. Paper 1 (THEORY)

Financial Management System

Java (12 Weeks) Introduction to Java Programming Language

AP Computer Science Java Mr. Clausen Program 9A, 9B

Queues and Stacks. Atul Prakash Downey: Chapter 15 and 16

Course: Programming II - Abstract Data Types. The ADT Queue. (Bobby, Joe, Sue, Ellen) Add(Ellen) Delete( ) The ADT Queues Slide Number 1

Scoping (Readings 7.1,7.4,7.6) Parameter passing methods (7.5) Building symbol tables (7.6)

Java Interfaces. Recall: A List Interface. Another Java Interface Example. Interface Notes. Why an interface construct? Interfaces & Java Types

Linked Lists: Implementation Sequences in the C++ STL

Description: Maintenance review of the JDBC RowSets 1.0 Specification. Feedback: Comments should be sent to

Specialized Programme on Web Application Development using Open Source Tools

Fundamentals of Java Programming

Introduction to Object-Oriented Programming

Using the Monitoring and Report Viewer Web Services

Parallel Programming

Mobile App Design Project #1 Java Boot Camp: Design Model for Chutes and Ladders Board Game

7. Object-Oriented Programming

TESTING WITH JUNIT. Lab 3 : Testing

Quick Reference AP Computer Science A

Java Programming Language

JDK 1.5 Updates for Introduction to Java Programming with SUN ONE Studio 4

Class Overview. CSE 326: Data Structures. Goals. Goals. Data Structures. Goals. Introduction

Lecture 7: Class design for security

Transcription:

ArrayLists & List Computational Complexity

Generic Operations on a List n create an empty list n add(x) insert x at the end of the list n add(x, idx) inserts x into the list at the specified position n clear( ) removes all elements from the list n get(idx) returns the object at position idx n indexof(x) returns the position of the first occurrence of x n isempty( ) returns true if the list has no elements n printlist() prints all elements in the list n remove(idx) removes the element at idx n set(idx, x) replace the specified position with x n size() returns the number of elements in the list n... 2

Simple Array Implementation of a List n Use an array to store the elements of the list q q q printlist is O(n) add(x), get(idx) and set(idx, x) are constant time What about add(idx, x) and remove(idx)? n Also, arrays have a fixed capacity, but we can resize them by copying elements to a new larger array int arr[] = new int arr[10]; int newarr[] = new int[arr.length * 2]; for(int i = 0; i < arr.length; i++) newarr[i] = arr[i]; arr = newarr; // arr is now twice as large 3

Concrete Implementations of the List ADT in the Java Collections API n Two concrete implementations of the List API in the Java Collections API with which you are already familiar are: q java.util.arraylist q java.util.linkedlist n Let s examine the methods of these concrete classes that were developed at Sun. 4

A Graph of Growth Functions 5

Expanded Scale 6

List Operations on an ArrayList<E> n Supports constant time for q insertion at the end of the list using void add(e element) q deletion from the end of the list using E remove(int index) q access to any element of the list using E get(int index) q changing value of any element of the list using E set(int index, E element) 7

List Operations on an ArrayList<E> (cont.) What is the computational complexity for the following? q insertion at the beginning of the list using void add(int index, E element) q deletion from the beginning of the list using E remove(int index) 8

List Operations on a LinkedList<E> n Provides doubly-linked list implementation 9

List Operations on a LinkedList<E> n Supports constant time for: insertion at the beginning of the list using void addfirst(e o) insertion at the end of the list using void addlast(e o) deletion from the beginning of the list using E removefirst() deletion from the end of the list using E removelast() Accessing first element of the list using E getfirst() Accessing first element of the list using E getlast() q q q q q q 10

List Operations on a LinkedList<E> n What is the complexity for the following? q access to the middle element of the list using E get(int index) 11

Example 1 ArrayList vs. LinkedList n What is the running time for an ArrayList versus a LinkedList? public static void makelist1(list<integer> list, int N) { list.clear(); for(int i = 0; i < N; i++) list.add(i); 12

Example 2 ArrayList vs. LinkedList n What is the running time for an ArrayList versus a LinkedList? public static void makelist2(list<integer> list, int N) { list.clear(); for(int i = 0; i < N; i++) list.add(0,i); 13

Example 3 ArrayList vs. LinkedList n What is the running time for an ArrayList versus a LinkedList? public static int sum(list<integer> list, int N) { int total = 0; for(int i = 0; i < N ; i++) total += list.get(i); return total; n How can we change this code so the running time for both is the same? 14

Extra Material

Methods from the Collections List ADT //from Collection interface int size( ); boolean isempty( ); void clear( ); boolean contains( AnyType x ); boolean add( AnyType x ); boolean remove( AnyType x ); java.util.iterator<anytype> iterator( ); //from List interface AnyType get( int idx ); AnyType set( int idx, AnyType newval ); void add( int idx, AnyType x ); void remove( int idx ); ListIterator<AnyType> listiterator(int pos); 16

The Iterator<E> Interface n The Collections framework provides two very useful interfaces for traversing a Collection. The first is the Iterator<E> interface. n When the iterator method is called on a Collection, it returns an Iterator object which has the following methods for traversing the Collection. boolean hasnext( ); AnyType next( ); void remove( ); 17

Using an Iterator to Traverse a Collection public static <AnyType> void print(collection<anytype> coll) { Iterator<AnyType> itr = coll.iterator(); while(itr.hasnext()){ AnyType item = itr.next(); System.out.println(item); 18

The Enhanced for Loop n The enhanced for loop in Java actually calls the iterator method when traversing a Collection and uses the Iterator to traverse the Collection when translated into byte code. public static <AnyType> void print(collection<anytype> coll) { for(anytype item : coll) System.out.println(item); 19

The ListIterator<E> Interface n The second interface for traversing a Collection is the ListIterator<E> interface. It allows for the bidirectional traversal of a List. boolean hasprevious(); AnyType previous(); void add(anytype x); void set(anytype newval); n A ListIterator object is returned by invoking the listiterator method on a List. 20

Implementing Your Own ArrayList n What do you need? 1. Store elements in a parameterized array 2. Track number of elements in array (size) and capacity of array public class MyArrayList<AnyType> implements Iterable<AnyType> { private static final int DEFAULT_CAPACITY=10; private int thesize; private AnyType[] theitems; 21

3. Ability to change capacity of the array public void ensurecapacity(int newcapacity) { if (newcapacity < thesize) return; AnyType[] old = theitems; theitems = (AnyType[]) new Object[newCapacity]; for(int i = 0; i < size(); i++) theitems[i] = old[i]; 22

4. get and set Methods public AnyType get(int idx) { if(idx < 0 idx >= size()) throw new ArrayIndexOutOfBoundsException(); return theitems[idx]; public AnyType set(int idx, AnyType newval) { if(idx < 0 idx >= size()) throw new ArrayIndexOutOfBoundsException(); AnyType old = theitems[idx]; theitems[idx] = newval; return old; 23

5. size, isempty, and clear Methods public void clear(){ thesize = 0; ensurecapacity(default_capacity); public int size(){ return thesize; public boolean isempty(){ return size() == 0; // constructor invokes the clear method public MyArrayList(){ clear(); 24

6. add Methods public boolean add(anytype x) { add(size(), x); return true; public void add(int idx, AnyType x) { if(theitems.length == size()) ensurecapacity(size() * 2 + 1); for(int i = thesize; i > idx; i--) theitems[i] = theitems[i - 1]; theitems[idx] = x; thesize++; 25

7. remove and iterator Method public AnyType remove(int idx) { AnyType removeditem = theitems[idx]; for(int i = idx; i < size() - 1; i++) theitems[i] = theitems[i + 1]; thesize--; return removeditem; //required by Iterable<E> interface public java.util.iterator<anytype> iterator() { return new ArrayListIterator(); 26

8. Iterator class // private inner class for iterator private class ArrayListIterator implements java.util.iterator<anytype> { private int current = 0; public boolean hasnext() { return current < size(); public AnyType next() Implicit ref. to outer class data { return theitems[current++]; public void remove() { MyArrayList.this.remove(--current); // end MyArrayList class Implicit reference to outer class method Explicit reference to outer class method 27

Example 4 ArrayList vs. LinkedList n What is the running time for an ArrayList versus a LinkedList? public static void removeevensver3(list<integer> lst) { Iterator<Integer> itr = lst.iterator(); while(itr.hasnext()) if(itr.next() % 2 == 0) itr.remove(); 29