Agenda. Inner classes and implementation of ArrayList Nested classes and inner classes The AbstractCollection class Implementation of ArrayList!

Similar documents
Agenda. Inner classes and implementation of ArrayList Nested classes and inner classes The AbstractCollection class Implementation of ArrayList

package weiss.util; // Fig , pg // Fig 6.16,6.17, pg package weiss.util;

Abstract Data Types. Data Str. Client Prog. Add. Rem. Find. Show. 01/22/04 Lecture 4 1

Abstract Data Types. Data Str. Client Prog. Add. Rem. Find. Show. 01/30/03 Lecture 7 1

Abstract data types (again) Announcements. Example ADT an integer bag (next) The Java Collections Framework

CMSC 341. Linked Lists. Textbook Section 3.5

[Ref: Core Java Chp 13, Intro to Java Programming [Liang] Chp 22, Absolute Java Chp 16, docs.oracle.com/javase/tutorial/collections/toc.

Implementation. Learn how to implement the List interface Understand the efficiency trade-offs between the ArrayList and LinkedList implementations

Class 32: The Java Collections Framework

Java Collection Framework

Lecture 6 Collections

Collections (Java) Collections Framework

Collections and Maps

CMSC 341. Linked Lists, Stacks and Queues. CMSC 341 Lists, Stacks &Queues 1

COMP6700/2140 Abstract Data Types: Queue, Set, Map

Linear Structures. Linear Structure. Implementations. Array details. List details. Operations 4/18/2013

Java Collections Framework: Interfaces

11. Collections of Objects

Linear Structures. Linear Structure. Implementations. Array details. List details. Operations 2/10/2013

An Interface with Generics

CS350: Data Structures Stacks

Type Parameters: E - the type of elements returned by this iterator Methods Modifier and Type Method and Description

Collections class Comparable and Comparator. Slides by Mark Hancock (adapted from notes by Craig Schock)

Lecture 15 Summary. Collections Framework. Collections class Comparable and Comparator. Iterable, Collections List, Set Map

Sets and Maps. Part of the Collections Framework

Standard ADTs. Lecture 19 CS2110 Summer 2009

Lists. CSC212 Lecture 8 D. Thiebaut, Fall 2014

Generics Collection Framework

1 P age DS & OOPS / UNIT II

Lists. The List ADT. Reading: Textbook Sections

Framework. Set of cooperating classes/interfaces. Example: Swing package is framework for problem domain of GUI programming

Programming II (CS300)

Notes on access restrictions

infix expressions (review)

Important Dates. Game State and Tree. Today s topics. Game Tree and Mini-Max. Games and Mini-Max 3/20/14

csci 210: Data Structures Stacks and Queues

Arrays organize each data element as sequential memory cells each accessed by an index. data data data data data data data data

LINKED LISTS cs2420 Introduction to Algorithms and Data Structures Spring 2015

What is the Java Collections Framework?

Collections and Iterators. Collections

CONTAİNERS COLLECTİONS

Lecture 15 Summary 3/11/2009. By the end of this lecture, you will be able to use different types of Collections and Maps in your Java code.

Java Collections. Readings and References. Collections Framework. Java 2 Collections. References. CSE 403, Winter 2003 Software Engineering

엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University

CS 310: Array-y vs Linky Lists

HOWDY! WELCOME TO CSCE 221 DATA STRUCTURES AND ALGORITHMS

Topic #9: Collections. Readings and References. Collections. Collection Interface. Java Collections CSE142 A-1

1/18/12. Chapter 5: Stacks, Queues and Deques. Stacks. Outline and Reading. Nancy Amato Parasol Lab, Dept. CSE, Texas A&M University

Programming II (CS300)

Computer Science CS221 Test 4 Name

Introduction to Software Design

Collections (Collection Framework) Sang Shin Java Technology Architect Sun Microsystems, Inc.

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

JCF: user defined collections

CH ALGORITHM ANALYSIS CH6. STACKS, QUEUES, AND DEQUES

17. Java Collections. Organizing Data. Generic List in Java: java.util.list. Type Parameters ( Parameteric Polymorphism ) Data Structures that we know

Generic classes & the Java Collections Framework. *Really* Reusable Code

CSC 1214: Object-Oriented Programming

CSE 373 Data Structures and Algorithms. Lecture 2: Queues

Computer Science 62. Bruce/Mawhorter Fall 16. Midterm Examination. October 5, Question Points Score TOTAL 52 SOLUTIONS. Your name (Please print)

Insertions and removals follow the Fist-In First-Out rule: Insertions: at the rear of the queue Removals: at the front of the queue

CSE 143 SAMPLE MIDTERM

03/29/2004. A dispenser has three essential features: adding, removing, accessing. Dispensers

Overview of Java ArrayList, HashTable, HashMap, Hashet,LinkedList

DNHI Homework 3 Solutions List, Stacs and Queues

Functors. 01/23/03 Lecture 5 1

Vector (Java 2 Platform SE 5.0) Overview Package Class Use Tree Deprecated Index Help

16-Dec-10. Collections & Data Structures ABSTRACTION VS. IMPLEMENTATION. Abstraction vs. Implementation

CS 231 Data Structures and Algorithms Fall DDL & Queue Lecture 20 October 22, Prof. Zadia Codabux

Java Magistère BFA

Queues COL 106. Slides by Amit Kumar, Shweta Agrawal

Abstract Data Types (ADTs) Example ADTs. Using an Abstract Data Type. Class #08: Linear Data Structures

DM550 / DM857 Introduction to Programming. Peter Schneider-Kamp

Queues Fall 2018 Margaret Reid-Miller

Java collections framework

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

Abstract vs concrete data structures HEAPS AND PRIORITY QUEUES. Abstract vs concrete data structures. Concrete Data Types. Concrete data structures

Introduction to Computer Science II (ITI 1121) Final Examination

Data Structures I: Linked Lists

EXAMINATIONS 2012 Trimester 1, MID-TERM TEST. COMP103 Introduction to Data Structures and Algorithms SOLUTIONS

Converting Collections to Arrays. A Bad Approach to Array Conversion. A Better Approach to Array Conversion. public Object[] toarray();

Lists, Stacks, and Queues. (Lists, Stacks, and Queues ) Data Structures and Programming Spring / 50

THE UNIVERSITY OF WESTERN AUSTRALIA

Abstract Data Types. Definitions, Implementations, and Uses

Practical Session 3 Java Collections

How to Win Coding Competitions: Secrets of Champions. Week 2: Computational complexity. Linear data structures Lecture 5: Stack. Queue.

Inner Classes. CMSC 433 Programming Language Technologies and Paradigms Spring Example: The Queue Class. Example: The Queue Class (cont d)

Introduction to Collections

CS200: Queues. Prichard Ch. 8. CS200 - Queues 1

Collections. James Brucker

EXAMINATIONS 2015 COMP103 INTRODUCTION TO DATA STRUCTURES AND ALGORITHMS

2. The actual object type stored in an object of type CollectionClassName<E> is specified when the object is created.

The Java Collections Framework. Chapters 7.5

ITI Introduction to Computing II

Building Java Programs

The Java Collections Framework and Lists in Java Parts 1 & 2

8. Fundamental Data Structures

Java Collections Framework. 24 April 2013 OSU CSE 1

Data structure and algorithm in Python

Data Structures. Outline. Introduction Linked Lists Stacks Queues Trees Deitel & Associates, Inc. All rights reserved.

Transcription:

Implementations I 1

Agenda Inner classes and implementation of ArrayList Nested classes and inner classes The AbstractCollection class Implementation of ArrayList! Stack and queues Array-based implementations Linked list-based implementations Linked lists Doubly linked lists, circularly linked lists, sorted linked lists 2

Iterator design using nested class Notice the static specification 3

Iterator design using inner class 4

5

Nested classes and inner classes A static nested class interacts with the instance members of its outer class (and other classes) just like any other top-level class. In effect, a static nested class is behaviorally a top-level class that has been nested in another top-level class for packaging convenience. As with instance methods and variables, an inner class is associated with an instance of its enclosing class and has direct access to that object's methods and fields. 6

Abstract collections A set is an unordered collection of elements. No duplicates are allowed. A list is an ordered collection of elements. Duplicates are allowed. Lists are also known an sequences. A map is an unordered collection of key-value pairs. The keys must be unique. Maps are also known as dictionaries. 7

Interfaces for collections java.util.* Collection Map Set List SortedMap SortedSet 8

interface Collection<E>! boolean add(e o)!! boolean addall(collection<? extends E> c)!! void clear()!! boolean contains(object o)!! boolean containsall(collection<?> c)!! boolean isempty()!! Iterator<E> iterator()!! boolean remove(object o)!! boolean removeall(collection<?> c)!! boolean retainall(collection<?> c)!! int size()!! Object[] toarray()!! <T> T[] toarray(t[] a)! 9

of 3 10

11

Flaw A Collection may contain itself! 12

tostring as implemented in java.util.abstractcollection! public String tostring() {! Iterator<E> it = iterator();! if (! it.hasnext())! return "[]";!! StringBuilder sb = new StringBuilder();! sb.append('[');! for (;;) {! E e = it.next();! sb.append(e == this? "(this Collection)" : e);! if (! it.hasnext())! return sb.append(']').tostring();! sb.append(',').append(' ');! }! }! 13

ArrayList An array list (ArrayList) is a list that uses an array to store its elements. Collection italic: interface normal: class AbstractCollection List implements! ArrayList extends! 14

of 3 modcount represents the number of structural modifications (adds, removes) made to the ArrayList. The idea is that when an iterator is constructed, the iterator saves this value in its data member expectedmodcount. When any iterator operation is performed, the iterator s expectedmodcount member is compared with the ArrayList s modcount, and if they disagree, a ConcurrentModificationException can be thrown. 15

idx! 16

listiterator(int idx): Returns a list iterator of the elements in this list (in proper sequence), starting at the specified position in this list. The specified index indicates the first element that would be returned by an initial call to the next method. An initial call to the previous method would return the element with the specified index minus one. 17

18

Does either of these proposed implementations of clear for AbstractCollection work? ); Version #1 will throw a ConcurrentModificationException! Version #2 works! 19

Does this proposed implementation of clear work? public void clear( ) // Version #3! {! Iterator<AnyType> itr = iterator( );! while( itr.hasnext( ) )! itr.remove( );! }! Version #3 will throw an IllegalStateException! public void clear( ) // Version #4! {! Iterator<AnyType> itr = iterator( );! while( itr.hasnext( ) )! itr.next( ).remove( );! }! Version #4 works! 20

Stacks and queues 21

Stack (LIFO = LastInFirstOut) A stack is a sequence of items of the same type that provides the following two operations: push(x):!add the item x to the top of the stack!pop: Remove the top item from the stack push! pop! Only the topmost item on the stack (top) is accessible stack 22

Stack implemented with an array The integer tos (top of stack) provides the array index of the top element of the stack 23

24

25

26

27

28

Amortized running time Array doubling is expensive in running time: O(N). However, array doubling is infrequent because an array doubling that involves N elements must be preceded by at least N/2 pushes that do not involve an array doubling. Consequently we can charge the O(N) cost of the doubling over these N/2 easy pushes, thereby effectively raising the cost of each push by only a small constant. In the long run push runs in O(1) time. Amortization: The paying off of debt in regular installments over a period of time. 29

Stack implemented with a linked list topofstack ListNode! element! next! class ListNode<AnyType> {! ListNode(AnyType e, ListNode n) { element = e; next = n; }! }! AnyType element;! ListNode next;!! 30

31

32

33

O(1) amortized time O(1) time top 34

Class Stack in java.util! A more complete and consistent set of LIFO stack operations is provided by the Deque (double-ended queue) interface and its implementations, which should be used in preference to this class. 35

Queue (FIFO = FirstInFirstOut) A queue is a sequence of items of the same type that provides the following two operations: enqueue(x): Insert the item x at the back of the queue!dequeue: Remove the item at the front of the queue dequeue! enqueue! Only the item at the front of the queue (front) is accessible queue 36

Queue implemented with a linked list front back! ListNode! class ListNode<AnyType) {! ListNode(AnyType e) { element = e; }! }! AnyType element;! ListNode next;!! 37

38

39

O(1) time Note the execution order (right-to-left) O(1) time 40

back = back.next = new ListNode<AnyType>( x );! 41

42

Queue implemented with an array front = 0 back = 5 0 1 2 3 4 5 6 7 We must avoid shifting the items when an dequeue operation is executed. 43

Circular array front = 2 back = 5 currentsize = 4 0 1 2 3 4 5 6 7 dequeue: front = 3 back = 5 currentsize = 3 0 1 2 3 4 5 6 7 44

enqueue: front = 3 back = 6 currentsize = 4 0 1 2 3 4 5 6 7 enqueue with wraparound back = 0 front = 3 currentsize = 6 0 1 2 3 4 5 6 7 45

46

47

48

49

50

51

O(1) amortized time 52

53

O(1) time O(1) time 54

55

Interface Queue in java.util! Some implementing classes: LinkedList, PriorityQueue! 56

Linked lists 57

Disadvantages of storing a sequence of items as an array (1) Insertion and removal of items take time proportional to the length of the array (2) Arrays have a fixed length

Singly linked list 59

Insertion current.next = new ListNode(x, current.next);! 60

Deletion current.next = current.next.next;! 61

Using a header node for easy removal of the first element 62

non-standard 63

64

65

66

67

68

69

70

71

Doubly linked list 72

Insertion current! 5! newnode = new DoublyLinkedListNode(x);! newnode.prev = current;!!!!!// 1! newnode.next = current.next;!!!!// 2! current.next = newnode;!!!!!// 3! newnode.next.prev = newnode;!!!!// 4! current = newnode;!!!!!!// 5! 73

Deletion current! current.prev.next = current.next; // set a's next link! current.next.prev = current.prev; // set b's prev link! current.next = current.prev = null;! current = head;!!!!! // So current is not stale! 74

Circularly linked list 75

SortedLinkedList! 76

77

78

79

80

81

82

83

84

85

86

87

88

89