ADSA: Collections/4 1 241-423 Advanced Data Structures and Algorithms Objective –give an overview of Collection classes, and create/use a Bag class Semester.

Slides:



Advertisements
Similar presentations
Transparency No. 1 Java Collection API : Built-in Data Structures for Java.
Advertisements

Lists and the Collection Interface Chapter 4. Chapter Objectives To become familiar with the List interface To understand how to write an array-based.
Data Structures A data structure is a collection of data organized in some fashion that permits access to individual elements stored in the structure This.
CS252: Systems Programming Ninghui Li Program Interview Questions.
Elementary Data Structures CS 110: Data Structures and Algorithms First Semester,
COP3538 – Data Structures Using OOP Chapter 4 – Stacks and Queues.
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures for Java William H. Ford William R. Topp Chapter 11 Implementing.
Stack and Queue Dr. Bernard Chen Ph.D. University of Central Arkansas.
1 Chapter 24 Lists Stacks and Queues. 2 Objectives F To design list with interface and abstract class (§24.2). F To design and implement a dynamic list.
CS 307 Fundamentals of Computer Science 1 Abstract Data Types many slides taken from Mike Scott, UT Austin.
15-Jun-15 Lists in Java Part of the Collections Framework.
Lists and the Collection Interface Chapter 4. Chapter 4: Lists and the Collection Interface2 Chapter Objectives To become familiar with the List interface.
Fall 2007CS 2251 Lists and the Collection Interface Chapter 4.
TCSS 342, Winter 2005 Lecture Notes
Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 20 Lists, Stacks, Queues, and Priority.
12-Jul-15 Lists in Java Part of the Collections Framework.
Java's Collection Framework
Lists, Stacks, Queues Svetlin Nakov Telerik Corporation
SEG4110 – Advanced Software Design and Reengineering TOPIC G Java Collections Framework.
ADSA: Maps/ Advanced Data Structures and Algorithms Objectives – –examples of maps, and introduce map collection views Semester 2,
Abstract Data Types (ADTs) and data structures: terminology and definitions A type is a collection of values. For example, the boolean type consists of.
Chapter 3 List Stacks and Queues. Data Structures Data structure is a representation of data and the operations allowed on that data. Data structure is.
Data Structures and Abstract Data Types "Get your data structures correct first, and the rest of the program will write itself." - David Jones.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 22 Java Collections.
Collections F The limitations of arrays F Java Collection Framework hierarchy  Use the Iterator interface to traverse a collection  Set interface, HashSet,
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 22 Java Collections.
Containers Overview and Class Vector
(c) University of Washington14-1 CSC 143 Java Collections.
Jan 12, 2012 Introduction to Collections. 2 Collections A collection is a structured group of objects Java 1.2 introduced the Collections Framework Collections.
Generalized Containers CSIS 3701: Advanced Object Oriented Programming.
Main Index Contents 11 Main Index Contents Week 3 – The Vector Container.
GENERIC COLLECTIONS. Type-Wrapper Classes  Each primitive type has a corresponding type- wrapper class (in package java.lang).  These classes are called.
111 © 2002, Cisco Systems, Inc. All rights reserved.
C++ STL CSCI 3110.
Chapter 18 Java Collections Framework
LinkedList Many slides from Horstmann modified by Dr V.
Data structures Abstract data types Java classes for Data structures and ADTs.
CSS446 Spring 2014 Nan Wang  Java Collection Framework ◦ LinkedList ◦ Set ◦ Map 2.
1/20/03A2-1 CS494 Interfaces and Collection in Java.
ADSA: Linked Lists/ Advanced Data Structures and Algorithms Objective – –implement and use linked lists Semester 2, Linked.
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures for Java William H. Ford William R. Topp Chapter 8 Collection.
Collections in Java. 2 Collections Hierarchy > ArrayListVector Stack LinkedList > Arrays Collections.
Data Structures and Algorithms Lecture 1 Instructor: Quratulain Date: 1 st Sep, 2009.
13-1 Sets, Bags, and Tables Exam 1 due Friday, March 16 Wellesley College CS230 Lecture 13 Thursday, March 15 Handout #23.
CIS3023: Programming Fundamentals for CIS Majors II Summer 2010 Ganesh Viswanathan Generics and Collections Course Lecture Slides 19 th July 2010 “Never.
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures for Java William H. Ford William R. Topp Chapter 13 Implementing.
Standard Template Library The Standard Template Library was recently added to standard C++. –The STL contains generic template classes. –The STL permits.
Introduction to the Standard Template Library (STL) A container class holds a number of similar objects. Examples: –Vector –List –Stack –Queue –Set –Map.
Collections Data structures in Java. OBJECTIVE “ WHEN TO USE WHICH DATA STRUCTURE ” D e b u g.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 20 Lists, Stacks, Queues, and Priority.
Week 2 - Friday.  What did we talk about last time?  Computing Big Oh.
List Interface and Linked List Mrs. Furman March 25, 2010.
Chapter 5 Array-Based Structures © 2006 Pearson Education Inc., Upper Saddle River, NJ. All rights reserved.
CMSC 202 Containers and Iterators. Container Definition A “container” is a data structure whose purpose is to hold objects. Most languages support several.
University of Limerick1 Collections The Collection Framework.
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures for Java William H. Ford William R. Topp Chapter 12 Iterators.
3-1 Java's Collection Framework Another use of polymorphism and interfaces Rick Mercer.
Click to edit Master text styles Stacks Data Structure.
Java Collections Framework The client view. The Big Picture.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java From Control Structures through Data Structures by.
Collections ABCD ABCD Head Node Tail Node array doubly linked list Traditional Arrays and linked list: Below is memory representation of traditional.
Set Collection A Bag is a general collection class that implements the Collection interface. A Set is a collection that resembles a Bag with the provision.
Chapter 20 Lists, Stacks, Queues, and Priority Queues
Chapter 20 Lists, Stacks, Queues, and Priority Queues
Collections Framework
Sieve of Eratosthenes The Sieve of Eratosthenes uses a bag to find all primes less than or equal to an integer value n. Begin by creating a bag an inserting.
Introduction to Data Structure
Chapter 20 Lists, Stacks, Queues, and Priority Queues
Presentation transcript:

ADSA: Collections/ Advanced Data Structures and Algorithms Objective –give an overview of Collection classes, and create/use a Bag class Semester 2, Collection Types

ADSA: Collections/4 2 Contents 1. What is a Collection? 2. (Some of ) Ford & Topp's Collections 3. The Bag Class 4. Sieve of Eratosthenes 5. Implementing the Bag Class 6. Iterators 7. The JDK's Collection Classes

ADSA: Collections/ What is a Collection? A collection is an object that stores other objects. It includes operations for adding and removing objects and for accessing and updating their data.

ADSA: Collections/ (Some of ) Ford & Topp's Collections = interface/abstract class = (concrete) class implements/extends OrderedList

ADSA: Collections/4 5 The Collection Interface continued

ADSA: Collections/4 6 continued I'll explain iterators in a later part. Ford &Topp 'error'; not mine

ADSA: Collections/4 7

8 The List Interface The List interface extends the Collection interface by adding index-based operations. These allow for insertion, deletion, access, and updates at an index position in the list.

ADSA: Collections/4 9 The ArrayList Class An ArrayList stores element in a contiguous block of memory (like an array). But it is dynamic –it automatically expands when new elements are inserted An ArrayList is a direct-access structure –an operation can directly access any element continued

ADSA: Collections/4 10 Inserts and deletes at the right hand end of the list are O(1) Operations at other positions are O(n) since the rest of the list must be moved –shifted right for insertion –shifted left for deletion

ADSA: Collections/4 11 The LinkedList Class A LinkedList is a sequence whose elements are directly linked to adjacent elements in the sequence. A LinkedList is a sequential- access structure –an operation must move through the list to reach a particular element continued

ADSA: Collections/4 12 Insertion or deletion involves altering the links that connect the elements in the list –O(1) operations The OrderedList class is an extension of the List class that stores its elements in order. The OrderedList class is an extension of the List class that stores its elements in order.

ADSA: Collections/4 13 The Set Class A Set is a collection of elements where duplicates are not allowed. Includes mathematical set operations such as union, intersection, and difference. setA ∩ setB

ADSA: Collections/4 14 The Map Class A Map is a collection of key-value pairs –the key uniquely identifies the pair while the value field holds its data (another object) Access to a pair requires the key, and returns the value. A Map is often called an associative array.

ADSA: Collections/4 15 The Stack Class An element can only be added (pushed) and removed (popped) from the top of the stack. Elements come off a stack in the reverse order of their insertion –a stack has a Last-In-First-Out (LIFO) ordering

ADSA: Collections/4 16 The Queue Class Items enter the queue at the back and exit from the front. Elements come off a queue in the same order as their insertion –a queue has First-In-First-Out (FIFO) ordering

ADSA: Collections/4 17 The Priority Queue A priority queue is just like a queue, except for its removal operation. –the operation removes the maximum (or minimum) value, depending on the type of the priority queue

ADSA: Collections/4 18 The Graph and DiGraph Classes A Graph is a set of vertices connected by links, called edges. The edges may have weights. A digraph has directed edges.

ADSA: Collections/ The Bag Class A Bag may contain duplicate elements (unlike a Set). grab() returns a random element from the collection.

ADSA: Collections/4 20 Using Bag Find distinct characters in an input string and display them in alphabetical order. Enter a string: mississippi Sorted letters: [i, m, p, s] ms i p bag A m i i i i s s s s p p imps bag B array grab add remove dups sort

ADSA: Collections/4 21 Code import ds.util.Bag; import ds.util.Arrays; import java.util.Scanner; public class UseBag { public static void main(String[] args) { Scanner keyIn = new Scanner(System.in); :

ADSA: Collections/4 22 // prompt for input string System.out.print("Enter a string: "); String str = keyIn.next(); // create bags big enough for input string Bag bagA = new Bag ( str.length() ); Bag bagB = new Bag ( str.length() ); // add chars from input string to bagA for (int i = 0; i < str.length(); i++) bagA.add(str.charAt(i)); :

ADSA: Collections/4 23 Character ch; boolean foundDuplicate; while (!bagA.isEmpty()) { // move a random char from bagA to bagB ch = bagA.grab(); bagB.add(ch); // remove all other occurrences of char from bagA do foundDuplicate = bagA.remove(ch); while (foundDuplicate); } :

ADSA: Collections/4 24 // create array from bagB; sort it; output Object[] objArr = bagB.toArray(); Arrays.sort(objArr); System.out.println("Sorted letters: " + Arrays.toString(objArr)); } // end of main() } // end of UseBag class

ADSA: Collections/ Sieve of Eratosthenes The Sieve of Eratosthenes uses a bag to find all primes ≤ an integer n. It begins by creating a bag for all the values from 2 to n. Then it removes all multiples of 2, 3, 4, etc. from the bag. Eventually only prime numbers are left. continued air – a – toss – the - nees

ADSA: Collections/4 26 The sieve of Eratosthenes finding all the prime numbers in the range 2 to 25: array isn't a good d.s. choice due to space wastage

ADSA: Collections/4 27 Using the Sieve import ds.util.Bag; public class UseSieve { public static void main(String[] args) { Bag bag = sieve(500); Object[] arr = bag.toArray(); Arrays.sort(arr); writePrimes(arr); } Display all primes from 2 to 500.

ADSA: Collections/4 28 public static Bag sieve(int n) { Bag primeBag = new Bag (n); // fill the set with integers 2, 3,..., n for (int m = 2; m <= n; m++) primeBag.add( new Integer(m) ); :

ADSA: Collections/4 29 // find the primes from 2 to sqrt(n) for (int m = 2; m*m <= n; m++) { // if m is in the set then remove its multiples if(primeBag.contains( new Integer(m) )) { // make i go through 2*m, 3*m,... int i = 2*m; while (i <= n) { primeBag.remove( new Integer(i) ); i += m; // set i to next m multiple } return primeBag; } composite is k*j == n if k > then j must be < composite is k*j == n if k > then j must be <

ADSA: Collections/4 30 public static void writePrimes(Object[] arr) // nicely print the array elements { String intStr; int count = 1; StringBuffer sb = new StringBuffer(" "); for (int i=0; i < arr.length; i++) { intStr = arr[i].toString(); // int --> string // place intStr into string buffer, then print sb.replace(0, intStr.length(), intStr); System.out.print(sb.toString()); :

ADSA: Collections/4 31 // every 10 elements output a newline if(count % 10 == 0) System.out.println(); count++; } System.out.println(); } // end of writePrimes() } // end of UseSieve class

ADSA: Collections/4 32 Execution

ADSA: Collections/ Implementing the Bag Class public class Bag implements Collection { private T[] bagArr; // storage private int bagSize; // size of collection private Random rnd; // used by grab() : The Bag class uses a fixed-size array as its storage structure.

ADSA: Collections/4 34 public Bag(int capacity) { bagArr = (T[])new Object[capacity]; bagSize = 0; rnd = new Random(); } public String toString() { Object[] arr = toArray(); // copy elems into an array return Arrays.toString(arr); // return array as a string }

ADSA: Collections/4 35 public boolean remove(Object item) { for (int i=0; i < bagSize; i++) if (bagArr[i].equals(item)) { // find item remove(i); return true; } return false; } private void remove(int i) /* Remove bagArr[i] by moving the array elems left one position and decrementing bag size */ { for (int j=i; j < bagSize-1; j++) bagArr[j] = bagArr[j+1]; // copy elems to left bagSize--; }

ADSA: Collections/4 36 public boolean add(T item) { if (bagSize >= bagArr.length) // bag is full return false; else { // add item at end of bag bagArr[bagSize] = item; bagSize++; return true; } } // end of add() public T grab() // return random value from bag in range (0,bagSize) { if (bagSize == 0) // bag is empty return null; else return bagArr[rnd.nextInt(bagSize)]; } // end of grab() } // end of Bag class

ADSA: Collections/ Iterators An iterator is an object that can access the elements of a collection in an efficient and simple manner. –making data public in a collection is not simple later

ADSA: Collections/4 38 The Iterator interface defines the methods that are available to an iterator. Every collection data structure that implements the Collection interface also implements the Iterator interface –e.g. List has a ListIterator The Iterator Interface continued

ADSA: Collections/4 39 continued

ADSA: Collections/4 40 An iterator for a collection is created by the Collection.iterator() method –it returns an Iterator object that points to the beginning of the collection continued

ADSA: Collections/4 41 Create a collection: // create a linked list of integers LinkedList aList =...; Create an iterator() for the collection that you want to scan: Iterator iter = aList.iterator(); Collection.iterator() is called a factory method –a non-constructor method that creates objects

ADSA: Collections/4 42 Iterator Methods Iterator.hasNext() indicates whether more values remain in a collection scan. // continue while there are remaining elements while (iter.hasNext()) {... } Ford & Topp's iter arrows are misleading; I've changed them. later...

ADSA: Collections/4 43 Iterator.next() returns the value of the next collection element and moves forward to just after the next element. –calling next() when hasNext() is false results in a NoSuchElementException continued

ADSA: Collections/4 44 Standard code for scanning a collection: // initialize iter to start of collection c iter = c.iterator(); // loop through elements to end of collection while (iter.hasNext()) { value = iter.next(); // get value and move forward // do something with value } continued

ADSA: Collections/4 45 The Iterator method remove() applied after a call to next() removes the collection value that was previously returned by next().

ADSA: Collections/4 46 Iterator Interface API

ADSA: Collections/4 47 Using an Iterator Any collection class that implements the Collection interface must include iterators. An algorithm that relies on scanning (traversing) elements in a collection and extracting their values can be implemented using an iterator.

ADSA: Collections/4 48 max() public static T max (Collection c) { // create an iterator positioned at list start Iterator iter = c.iterator(); // assign maxValue the value of the first // element and advance iter T maxValue = iter.next(); // scan the rest of the elements in the collection while (iter.hasNext()) { T val = iter.next(); if (val.compareTo(maxValue) > 0) maxValue = val; } return maxValue; }

ADSA: Collections/ The JDK's Collection Classes The Java JDK contains two high level Interfaces related to collections: –java.util.Collection –java.util.Map Collections are used for collecting Java objects. Maps are used for mapping key/value pairs.

ADSA: Collections/4 50 The Collection Interface Use a Collection if you need to keep related objects together, and want to: –search for a particular element –list the elements –manipulate the order of the elements –access the elements by an index number –use collection basic operations, such as add, remove, update

ADSA: Collections/4 51 Set, List, and Queue Interfaces

ADSA: Collections/4 52 List in more Detail (JDK 6)

ADSA: Collections/4 53 Set in more Detail (JDK 6) NavigableSet: a set with navigation methods

ADSA: Collections/4 54 Queue in more Detail (JDK 6) deque (deck): insert/remove at both ends

ADSA: Collections/4 55 The Map Interface Use the Map interface to store pairs, and you want to: –access an element by a key object –map one object to other A Map can be thought of as an array where the index need not be an integer. –also called associated array, dictionary

ADSA: Collections/4 56 Map in Detail (JDK 6)

ADSA: Collections/4 57 Thread-safe Collections Many collection classes have implementations for both single-threaded programs (no concurrency) and multiple threaded programs (concurrent). continued Also called concurrent collections.

ADSA: Collections/4 58 List in Full Also Vector (but old fashioned)

ADSA: Collections/4 59 Set in Full

ADSA: Collections/4 60 Queue in Full (very full) BlockingQueue: v.useful for message passing between threads

ADSA: Collections/4 61 Map in Full Also Hashtable (but old fashioned)