Chapter 12 Data Structures and Collections. 2 Knowledge Goals Understand the difference between array and linked implementations of a list Know how to.

Slides:



Advertisements
Similar presentations
Java Programming: Advanced Topics 1 Collections and Utilities.
Advertisements

Transparency No. 1 Java Collection API : Built-in Data Structures for Java.
Chapter 24 Lists, Stacks, and Queues
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.
Chapter 6 The Collections API. Simple Container/ Iterator Simple Container Shape [] v = new Shape[10]; Simple Iterator For( int i=0 ; i< v.length ; i++)
Collections Framework A very brief look at Java’s Collection Framework David Davenport May 2010.
1 Jake’s Pizza Shop Owner Jake Manager Chef Brad Carol Waitress Waiter Cook Helper Joyce Chris Max Len.
Lecture 8 CS203. Implementation of Data Structures 2 In the last couple of weeks, we have covered various data structures that are implemented in the.
© 2006 Pearson Addison-Wesley. All rights reserved11 B-1 Chapter 11 (continued) Trees.
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.
Collections Sets - no duplicates Lists - duplicates allowed Maps - key / value pairs A collection is an Object which contains other Objects. There are.
© 2006 Pearson Addison-Wesley. All rights reserved16-1 Methods in the List Interface (Part 1 of 16)
Fall 2007CS 2251 Iterators and Tree Traversals. Fall 2007CS 2252 Binary Trees In a binary tree, each node has at most two subtrees A set of nodes T is.
Data Structures & Java Collections Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L15 (Chapter 22) Java Collections.
Marc Smith and Jim Ten Eyck
Chapter 19 Java Data Structures
SEG4110 – Advanced Software Design and Reengineering TOPIC G Java Collections Framework.
Geoff Holmes and Bernhard Pfahringer COMP206-08S General Programming 2.
Java Programming: Advanced Topics 1 Collections and Wealth of Utilities.
Chapter 9 Abstract Data Types and Algorithms. 2 Abstract Data Types Abstract data type A data type whose properties (data and operations) are specified.
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.
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.
CS Data Structures Chapter 15 Trees Mehmet H Gunes
CM0551 Exam Prep. What are an algorithm’s time and space complexity? (2 marks) Answer: The growth rate of the algorithm’s time requirement and the computer.
Jan 12, 2012 Introduction to Collections. 2 Collections A collection is a structured group of objects Java 1.2 introduced the Collections Framework Collections.
The Java Collections Framework (JCF) Introduction and review 1.
Information and Computer Sciences University of Hawaii, Manoa
© 2011 Pearson Addison-Wesley. All rights reserved 11 B-1 Chapter 11 (continued) Trees.
Chapter 18 Java Collections Framework
COMP 103 Linked Lists. 2 RECAP-TODAY RECAP  Linked Structures: LinkedNode  Iterating and printing Linked Nodes  Inserting and removing Linked Nodes.
Computer Science 209 Software Development Java Collections.
LinkedList Many slides from Horstmann modified by Dr V.
Data structures Abstract data types Java classes for Data structures and ADTs.
1 Chapter 17 Object-Oriented Data Structures. 2 Objectives F To describe what a data structure is (§17.1). F To explain the limitations of arrays (§17.1).
1/20/03A2-1 CS494 Interfaces and Collection in Java.
Chapter 8 Binary Search Trees. 2 Goals Define and use the following terminology: binary tree root descendant subtree binary search tree parent level ancestor.
Chapter 12: Collections by Lewis and Loftus (Updated by Dan Fleck) Coming up: Collections.
CS102 – Data Structures Lists, Stacks, Queues, Trees & HashTables. David Davenport.
This recitation 1 An interesting point about A3: Using previous methods to avoid work in programming and debugging. How much time did you spend writing.
Collections Data structures in Java. OBJECTIVE “ WHEN TO USE WHICH DATA STRUCTURE ” D e b u g.
1 Nell Dale Chapter 8 Binary Search Trees Modified from the slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus C++ Plus Data.
Data Structures Chapter 6. Data Structure A data structure is a representation of data and the operations allowed on that data. Examples: 1.Array 2.Record.
Computer Science and Software Engineering University of Wisconsin - Platteville 10. Binary Search Tree Yan Shi CS/SE 2630 Lecture Notes Partially adopted.
Collections Mrs. C. Furman April 21, Collection Classes ArrayList and LinkedList implements List HashSet implements Set TreeSet implements SortedSet.
© 2006 Pearson Addison-Wesley. All rights reserved5 B-1 Chapter 5 (continued) Linked Lists.
Copyright © 0 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java From Control Structures through Data Structures by Tony.
Week 15 – Wednesday.  What did we talk about last time?  Review up to Exam 1.
JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN © 2012 Pearson Education, Inc., Upper Saddle River,
1 Nell Dale Chapter 8 Binary Search Trees Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus C++ Plus Data Structures.
3-1 Java's Collection Framework Another use of polymorphism and interfaces Rick Mercer.
Collections ABCD ABCD Head Node Tail Node array doubly linked list Traditional Arrays and linked list: Below is memory representation of traditional.
Slides by Donald W. Smith
Chapter 12 – Data Structures
Trees Chapter 11 (continued)
Linked Lists Chapter 5 (continued)
Trees Chapter 11 (continued)
Chapter 19 Java Data Structures
Software Development Java Collections
Chapter 8 Binary Search Trees.
Chapter 17 Object-Oriented Data Structures
Map interface Empty() - return true if the map is empty; else return false Size() - return the number of elements in the map Find(key) - if there is an.
Lecture 12 CS203 1.
Collections Framework
Linked Lists Chapter 5 (continued)
Yan Shi CS/SE 2630 Lecture Notes
Presentation transcript:

Chapter 12 Data Structures and Collections

2 Knowledge Goals Understand the difference between array and linked implementations of a list Know how to a stack works Know how a queue works Know how a binary tree works Know how a hash table works Understand the concepts behind the java collections framework

3 Skill Goals Develop a linked data structure Use the ArrayList and LinkedList classes Use the HashSet and TreeSet classes Use the Stack class Use the LinkedList class to implement a queue Choose when to use an array-based versus a linked implementation of a data structure

4 Linked Structures Array- based list is fixed size

5 Linked Structures Array- based is physically ordered; linked is logically ordered, which means …

6 Linked Structures Insertions and deletions are easier

7 Linked Structure Linked list A list in which the order of the components is determined by an explicit link field in each node, rather than by the sequential order of the components in memory External reference (pointer) A named variable that references (points to) the first node (head) of a linked list Yes, but how does it work?

8 Linked Structure List A node Each node contains item and a link External pointer

9 Linked Structures class Node { Node link = null; String item; Node() { item = ""; } Node(String data) { item = data; } } null is a keyword meaning points to nothing default constructor parameterized constructor

10 Linked Structures Let's create a linked list with three nodes, containing "Adams", "Baker", and "Carter" We begin by creating two variables Node current; // Pointer used to keep track // of where we are in the list Node list; // External point to the list Result

11 Linked Structures list = new Node("Adams"); current = list; Result

12 Linked Structures current.link = new Node("Baker"); Result

13 Linked Structures current = current.link; Result

14 Linked Structures current.link = new Node("Carter"); current = current.link; Result

15 Linked Structures Traversal Visiting every node in a data structure following an organized pattern of access current = list; while (current.link != null) { System.out.println(current.item); current = current.link; } What is the pattern of access?

16 Linked Structures Which of these will change with the linked version?

17 Linked Structures Does the CRC card for a class change with the implementation?

18 Linked Structures Observer operations public boolean isEmtpy() { return list == null; } public boolean contains(String item) { Node current = list; while (current != null && curent.item.compareTo(item) != 0) curent = current.link; return current != null }

19 Linked Structures if (list.contains("Doggett"))… Search when item is not in the list

20 Linked Structures Size in an array-based list just returns numItems ; What about in a linked-implementation? –Can keep a counter increment with each insertion decrement with each deletion –Can count the number of items each time Which is best (better)?

21 Linked Structures public int size() { Node current = list; int numItems = 0; while (current != null) { numItems++; current = current.link; } return numItems; } Is this an example of a traversal?

22 Linked Structures Mutators Add –Insert where? To match array-based traversal, new item must go at the end –How to find end? Search or keep a pointer –Special case(s)? Empty list tail

23 Linked Structure public void add(String newItem) { Node item = new Node(newItem); if (list == null) { list = item; tail = item; } else { tail.link = item; tail = tail.link; } Empty list Set list and tail to item Not empty list Set item as last node Set tail to last node

24 Linked Structures Remove –Item not there? Do nothing –What if item is the first? Reset external pointer –What if item is the last? Reset tail pointer –What if item is anywhere else? General case

25 Linked Structures Can't be reached; System recaptures it

26 Linked Structures What is prior? Remove "Adams"

27 Linked Structures Remove "Carter"

28 Linked Structures Remove "Adams" (only node)

29 public void remove(String item) { Node current = list; Node prior = null; while (current != null && current.item.compareTo(item) != 0) { prior = current; current = current.link; } if (current != null) { if (current == tail) tail = prior; if (prior == null) list = list.link; else prior.link = current.link; } Search for item item in last node item in first node item in interior node

30 Linked Structures Iterator "trio" public void resetList() { current = list; } public boolean hasNext() { return current != null; } public String next() { String item = current.item; current = current.link; return item; } What assumptions must be in documentation?

31 Other Data Structures What do these objects have in common?

32 Other Data Structures Stack A data structure in which insertions and deletions can be made from only one end LIFO Last In First Out Can you name some additional LIFO structures in every day life?

33 Other Data Structures First item called "top"

34 Other Data Structures What properties does this illustration exhibit?

35 Other Data Structures Queue A data structure in which insertions are made at one end and deletions are made at the other end FIFO First In First Out Can you name some additional FIFO structures in every day life?

36 Other Data Structures

37 Other Data Structures

38 Owner Jake Manager Chef Brad Carol Waitress Waiter Cook Helper Joyce Chris Max Len Other Data Structures Jake's Pizza Shop What properties does this illustration exhibit?

39 Owner Jake Manager Chef Brad Carol Waitress Waiter Cook Helper Joyce Chris Max Len ROOT NODE Other Data Structures

40 Owner Jake Manager Chef Brad Carol Waitress Waiter Cook Helper Joyce Chris Max Len LEAF NODES Other Data Structures

41 Owner Jake Manager Chef Brad Carol Waitress Waiter Cook Helper Joyce Chris Max Len LEFT SUBTREE OF ROOT NODE Other Data Structures

42 Owner Jake Manager Chef Brad Carol Waitress Waiter Cook Helper Joyce Chris Max Len RIGHT SUBTREE OF ROOT NODE Other Data Structures

43 Other Data Structures Binary tree A data structure, each of whose nodes refer to left and right child nodes

44 Other Data Structures Binary search tree A binary tree in which the value in any node is greater than the value in the left child and any of its children and less than the value in its right child and any of its children

45 Other Data Structures Binary search trees provide rapid searches Search for 50

46 Other Data Structures Search for 18 Where would 18 be if there?

47 Other Data Structures Inorder(tree) if tree is not NULL Inorder(Left(tree)) Visit Info(tree) Inorder(Right(tree)) PostOrder(tree) if tree is not NULL Postorder(Left(tree)) Postorder(Right(tree)) Visit Info(tree) PreOrder(tree) if tree is not NULL Visit Info(tree) Preorder(Left(tree)) Preorder(Right(tree)) alphabetic order visits leaves first expression evaluation Traversals

48 Other Data Structures

49 Other Data Structures Graph A data structure in which the nodes can be arranged in any pattern

50 Other Data Structures Hashing A technique to perform insertions and access to an item in constant time by using the value to identify its location in the structure

51 Other Data Structures [ 0 ] [ 1 ] [ 2 ] [ 3 ] [ 4 ]. Empty 4501 Empty values [ 97] [ 98] [ 99] 7803 Empty. Empty HandyParts company makes no more than 100 different parts, but the parts all have four digit numbers index = partNum % 100 Hash function A function used to manipulate the value to produce an index that identifies its location

52 Use the hash function Hash(key) = partNum % 100 to place the element with part number 5502 in the array [ 0 ] [ 1 ] [ 2 ] [ 3 ] [ 4 ]. Empty 4501 Empty values [ 97] [ 98] [ 99] 7803 Empty. Empty Other Data Structures

53 Next place part number 6702 in the array 6702 % 100 = 2 But values[2] is already occupied, causing a collision [ 0 ] [ 1 ] [ 2 ] [ 3 ] [ 4 ]. values [ 97] [ 98] [ 99] 7803 Empty. Empty Empty Other Data Structures

54 One solution Repeatedly increment index until an empty location is found for part number 6702 [ 0 ] [ 1 ] [ 2 ] [ 3 ] [ 4 ]. values [ 97] [ 98] [ 99] 7803 Empty. Empty Empty Other Data Structures

55 Part 6702 can be placed at the location with index 4 [ 0 ] [ 1 ] [ 2 ] [ 3 ] [ 4 ]. values [ 97] [ 98] [ 99] 7803 Empty. Empty Empty Hashing

56 Part 6702 is placed at the location with index 4 Where would the part with number 4598 be placed using this scheme? [ 0 ] [ 1 ] [ 2 ] [ 3 ] [ 4 ]. values [ 97] [ 98] [ 99] Empty Empty Hashing

57 Other Data Structures Handling collisions with chaining

58 Other Data Structures Comparison of incrementing index and chaining

59 Generic Types in Java Generic types A type for which the operations are defined but the type of the objects being manipulated is not How have we handled generics previously?

60 Generic Types in Java class Node <ItemType extends Comparable > { Node link = null; ItemType item; Node() { } Node(ItemType newItem) { item = newItem; } } Node list; Node tail; In client code

61 Java Collections Framework Classes that implement Collection are data structures that hold items in an organized manner Set is Java's list with no duplicates Interface Hierarchy

62 Java Collections Framework Classes that implement Map hold values in association with objects called keys Rest of Interface hierarchy

63 Java Collections Framework Let's look at this another way

64 Collection List Set SortedSet AbstractCollection AbstractList AbstractSet AbstractSequentialList Interfaces Abstract Classes implements extends

65 AbstractListAbstractSet Abstract SequentialList LinkedList ArrayList VectorHashSetTreeSet Observers in AbstractCollection contains containsAll isEmpty toArray toString size Stack Linked HashSet Concrete Classes

66 Java Collections Framework AbstractCollections implements the Iterable Interface that has one method iterator that returns an Iterator object Iterator myIter = myList.iterator(); while (myIter.hasNext()) System.out.println(myIter.next());

67 Java Collections Framework Collections class contains static helper methods for use with the classes in the collection void sort(List) int binarySearch(List, key) void reverse(List) void shuffle(List) void copy(DestinationList, SourceList) Object min(Collection) Object max(Collection) boolean replaceAll(List, OldValueObject, NewValueObject) boolean disjoint(Collection, Collection)

68 Java Collections Framework ArrayList is a concrete list class using an array- based implementation with the usual list operations and some array-specific methods as well such as: add(index, item)Inserts the item at the index position set(index, item)Replaces the item at the index position; returns replaced object remove(index) Removes the item at the index position trimToSize()Trim array to list size ensureCapacity(limit) Makes sure the underlying array has limit positions

69 Java Collections Framework LinkedList is a concrete list class with a linked implementation with the usual list operations and some additional ones such as: add(index, item)Inserts item at the index position getFirst()Returns a reference to the first item getLast()Returns a reference to the last item poll()Deletes and returns the first element removeLast()Deletes and returns last element remove(index)Deletes and returns the item in the index position

70 Java Collections Framework ArrayList and LinkedList also have methods that take collections as arguments removeAll(collection)Removes all items from list that match items in collection retainAll(collection)Removes all items that do not match items in the collection addAll(collection)Adds all the items in the collection to the end of the list Do these operations add any new functionality?

71 Java Collections Framework Sets (a lists without duplicates) is implemented in two concrete classes: HashSet and TreeSet –Names give the underlying data structure –Both implement all the regular list operations –TreeSet is able to return subtrees (collections) with values less than or greater than a parameter

72 public static void main(String[] args) throws IOException { inFile = new Scanner(new FileReader("list.dat")); outFile = new PrintWriter(new FileWriter("list.out")); ArrayList list = new ArrayList(4); String line; while (inFile.hasNextLine()) { line = inFile.nextLine(); list.add(line); } Iterator iterator = list.iterator(); while (iterator.hasNext()) System.out.println(iterator.next()); What will the output look like?

73 Java Collections Framework File: red blue yellow brown black pink green orange white violet crimson rose Output: red blue yellow brown black pink green orange white violet crimson rose Output from ArrayList implementation

74 Java Collections Framework File: red blue yellow brown black pink green orange white violet crimson rose Output: green rose red white orange crimson pink brown blue yellow violet black HashSet list = new HashSet(); Output from HashSet implementation

75 Java Collections Framework File: red blue yellow brown black pink green orange white violet crimson rose Output: black blue brown crimson green orange pink red rose violet white yellow TreeSet list = new TreeSet(); Output from TreeSet implementation

76 Extras I designed one of the best known sorting algorithms and was knighted recently Who am I

77 Extras - GUI Track Handling events with radio buttons requires  declaring and instantiating a ButtonGroup object  declaring and instantiating each radio button  registering an ActionListener with each radio button  adding each button to ButtonGroup object  adding each button to panel  parameter to getActionCommand tells which button was pressed

78 Extras - GUI Track Window with three radio buttons and a label