Chapter 2 Collections. Copyright © 2004 Pearson Addison-Wesley. All rights reserved.1-2 Chapter Objectives Define the concept and terminology related.

Slides:



Advertisements
Similar presentations
Topic 12 The List ADT. 9-2 Objectives Examine list processing and various ordering techniques Define a list abstract data type Examine various list implementations.
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.
COMP 121 Week 9: AbstractList and ArrayList. Objectives List common operations and properties of Lists as distinct from Collections Extend the AbstractCollection.
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.
1 ADT and Data Structure Example Generics / Parameterized Classes Using a Set Implementing a Set with an Array Example: SetADT interface Example: ArraySet.
Topic 9 The Queue ADT.
Chapter 7 Queues. Copyright © 2004 Pearson Addison-Wesley. All rights reserved.1-2 Chapter Objectives Examine queue processing Define a queue abstract.
Chapter 5 Queues Modified. Chapter Scope Queue processing Comparing queue implementations 5 - 2Java Software Structures, 4th Edition, Lewis/Chase.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java From Control Structures through Data Structures by.
CHAPTER 3 COLLECTIONS Abstract Data Types. 2 A data type consists of a set of values or elements, called its domain, and a set of operators acting on.
CS 307 Fundamentals of Computer Science 1 Abstract Data Types many slides taken from Mike Scott, UT Austin.
Chapter 3 Collections. Copyright © 2005 Pearson Addison-Wesley. All rights reserved. 3-2 Chapter Objectives Define the concept and terminology related.
CHAPTER 8 Lists. 2 A list is a linear collection Adding and removing elements in lists are not restricted by the collection structure We will examine.
© 2006 Pearson Addison-Wesley. All rights reserved4-1 Chapter 4 Data Abstraction: The Walls.
CHAPTER 3 COLLECTIONS SET Collection. 2 Abstract Data Types A data type consists of a set of values or elements, called its domain, and a set of operators.
CHAPTER 6 Stacks Array Implementation. 2 Stacks A stack is a linear collection whose elements are added and removed from one end The last element to be.
Chapter 4 Linked Structures. Copyright © 2005 Pearson Addison-Wesley. All rights reserved. 4-2 Chapter Objectives Describe the use of references to create.
© 2006 Pearson Addison-Wesley. All rights reserved4-1 Chapter 4 Data Abstraction: The Walls.
Chapter 12 Trees. Copyright © 2005 Pearson Addison-Wesley. All rights reserved Chapter Objectives Define trees as data structures Define the terms.
Chapter 8 Lists. Copyright © 2005 Pearson Addison-Wesley. All rights reserved. 8-2 Chapter Objectives Examine list processing and various ordering techniques.
Chapter 6 Stacks. Copyright © 2005 Pearson Addison-Wesley. All rights reserved. 6-2 Chapter Objectives Examine stack processing Define a stack abstract.
Bag Implementations that Use Arrays Chapter 2 Copyright ©2012 by Pearson Education, Inc. All rights reserved.
Stacks, Queues, and Deques
Chapter 14 Queues. First a Review Queue processing Using queues to solve problems – Optimizing customer service simulation – Ceasar ciphers – Palindrome.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Chapter 12 Introduction to Collections - Stacks
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 7 Queues. Copyright © 2005 Pearson Addison-Wesley. All rights reserved. 7-2 Chapter Objectives Examine queue processing Define a queue abstract.
Topic 3 The Stack ADT.
Chapter 3 Introduction to Collections – Stacks Modified
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.
Chapter 8 Lists. Copyright © 2004 Pearson Addison-Wesley. All rights reserved.1-2 Chapter Objectives Examine list processing and various ordering techniques.
Bags Chapter 1 Copyright ©2012 by Pearson Education, Inc. All rights reserved.
Trees CSCI Objectives Define trees as data structures Define the terms associated with trees Discuss the possible implementations of trees Analyze.
© 2010 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of CHAPTER 3: Collections Java Software Structures: Designing and Using.
Arrays An array is a data structure that consists of an ordered collection of similar items (where “similar items” means items of the same type.) An array.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
Lecture4: Arrays Bohyung Han CSE, POSTECH CSED233: Data Structures (2014F)
Chapter 6 Stacks. Copyright © 2004 Pearson Addison-Wesley. All rights reserved.1-2 Chapter Objectives Examine stack processing Define a stack abstract.
© 2010 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of CHAPTER 5: Queues Java Software Structures: Designing and Using Data.
Chapter 15 Linked Data Structures Slides prepared by Rose Williams, Binghamton University Kenrick Mock University of Alaska Anchorage Copyright © 2008.
Chapter 3 Collections. Objectives  Define the concepts and terminology related to collections  Explore the basic structures of the Java Collections.
CMSC 202 Arrays 2 nd Lecture. Aug 6, Array Parameters Both array indexed variables and entire arrays can be used as arguments to methods –An indexed.
CS 367 Introduction to Data Structures Lecture 2 Audio for Lecture 1 is available Homework 1 due Friday, September 18.
M1G Introduction to Programming 2 3. Creating Classes: Room and Item.
1 Stacks (Continued) and Queues Array Stack Implementation Linked Stack Implementation The java.util.Stack class Queue Abstract Data Type (ADT) Queue ADT.
Data Design and Implementation. Definitions Atomic or primitive type A data type whose elements are single, non-decomposable data items Composite type.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
Topic 2 Collections. 2-2 Objectives Define the concepts and terminology related to collections Discuss the abstract design of collections.
CMSC 202 Containers and Iterators. Container Definition A “container” is a data structure whose purpose is to hold objects. Most languages support several.
JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN © 2012 Pearson Education, Inc., Upper Saddle River,
© 2006 Pearson Addison-Wesley. All rights reserved 1-1 Chapter 1 Review of Java Fundamentals.
© 2010 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of CHAPTER 15: Sets and Maps Java Software Structures: Designing and Using.
CS 367 Introduction to Data Structures Charles N. Fischer Fall s367.html.
Topic 13 Iterators. 9-2 Motivation We often want to access every item in a data structure or collection in turn We call this traversing or iterating over.
Collections Using Generics in Collections. 2 Chapter Objectives Define the concept and terminology related to collections Explore the basic structure.
Chapter 4 ADTs Stack and Queue. 4-2 Formal ADT Specifications The Java interface construct lets us collect together method interfaces into a syntactic.
M180: Data Structures & Algorithms in Java Stacks Arab Open University 1.
1 Stacks Abstract Data Types (ADTs) Stacks Application to the analysis of a time series Java implementation of a stack Interfaces and exceptions.
Data Abstraction: The Walls
The List ADT.
The Stack ADT. 3-2 Objectives Define a stack collection Use a stack to solve a problem Examine an array implementation of a stack.
Java Software Structures: John Lewis & Joseph Chase
ArraySet Methods and ArrayIterator
Abstract Class As per dictionary, abstraction is the quality of dealing with ideas rather than events. For example, when you consider the case of ,
Adapted from Pearson Education, Inc.
Example: LinkedSet<T>
Copyright ©2012 by Pearson Education, Inc. All rights reserved
CHAPTER 3: Collections—Stacks
Presentation transcript:

Chapter 2 Collections

Copyright © 2004 Pearson Addison-Wesley. All rights reserved.1-2 Chapter Objectives Define the concept and terminology related to collections Explore the basic structure of the Java Collections API Discuss the abstract design of collections Define a bag collection Use a bag collection to solve a problem Examine an array implementation of a bag

Copyright © 2004 Pearson Addison-Wesley. All rights reserved.1-3 Collections A collection is an object that gathers and organizes other objects (elements) Many types of fundamental collections have been defined: stack, queue, list, tree, graph, etc. They can be broadly categorized as linear (organizes the elements in a straight line) or nonlinear

Copyright © 2004 Pearson Addison-Wesley. All rights reserved.1-4 figure 2.1 A linear and a nonlinear collection

Copyright © 2004 Pearson Addison-Wesley. All rights reserved.1-5 Collections The elements within a collection are usually organized based on: the order in which they were added to a collection, or some inherent relationship among the elements themselves For example, a list of people may be kept in alphabetical order by name or in the order in which they were added to the list Which type of collection you use depends on what you are trying to accomplish

Copyright © 2004 Pearson Addison-Wesley. All rights reserved.1-6 Abstraction An abstraction hides certain details at certain times It provides a way to deal with the complexity of a large system A collection, like any well-defined object, is an abstraction We want to separate the interface of the collection (how we interact with it) from the underlying details of how we choose to implement it

Copyright © 2004 Pearson Addison-Wesley. All rights reserved.1-7 figure 2.2 A well-defined interface masks the implementation of the collection

Copyright © 2004 Pearson Addison-Wesley. All rights reserved.1-8 Issues with Collections For each collection we examine, we will consider: How does the collection operate conceptually? How do we formally define its interface? What kinds of problems does it help us solve? What ways might we implement it? What are the benefits and costs of each implementation?

Copyright © 2004 Pearson Addison-Wesley. All rights reserved.1-9 Terms Various terms are used in the study of collections – defined in various ways Our definitions: data type – a group of values and the operations defined on those values abstract data type – a data type whose values and operations are not inherently defined in a programming language data structure – the programming constructs used to implement a collection

Copyright © 2004 Pearson Addison-Wesley. All rights reserved.1-10 The Java Collections API The Java Collections API is a set of classes that represent some specific collection types, implemented in various ways It is part of the large class library that can be used by any Java program API stands for Application Programming Interface As we explore various collections, we will examine the appropriate classes in the Java Collections API

Copyright © 2004 Pearson Addison-Wesley. All rights reserved.1-11 A Bag Collection Let's look at an example of a collection A bag collection groups elements without regard to their relationship to each other It's as if you threw them all in a bag You can reach into a bag and pull out an element, and are equally likely to get any one It is a nonlinear collection, but could be implemented with a linear data structure

Copyright © 2004 Pearson Addison-Wesley. All rights reserved.1-12 figure 2.3 The conceptual view of a bag collection

Copyright © 2004 Pearson Addison-Wesley. All rights reserved.1-13 Collection Operations Every collection has a set of operations that define how we interact with it They usually include ways for the user to: add and remove elements determine if the collection is empty determine the collection's size They also may include: iterators, to process each element in the collection operations that interact with other collections

Copyright © 2004 Pearson Addison-Wesley. All rights reserved.1-14 figure 2.4 The operations on a bag collection

Copyright © 2004 Pearson Addison-Wesley. All rights reserved.1-15 Java Interfaces The programming construct in Java called an interface is a convenient way to define the operations on a collection A Java interface lists the set of abstract methods (no bodies) that a class implements It provides a way to establish a formal declaration that a class will respond to a particular set of messages (method calls) See BagADT.java (page 38)BagADT.java

Copyright © 2004 Pearson Addison-Wesley. All rights reserved.1-16 figure 2.5 UML description of the BagADT interface

Copyright © 2004 Pearson Addison-Wesley. All rights reserved.1-17 Iterators An iterator is an object that allows the user to acquire and use each element in a collection in turn The program design determines: the order in which the elements are delivered the way the iterator is implemented In the case of a bag, there is no particular order to the elements, so the iterator order will be arbitrary (random)

Copyright © 2004 Pearson Addison-Wesley. All rights reserved.1-18 Iterators Collections that support iterators often have a method called iterator that returns an Iterator object Iterator is actually an interface defined in the Java standard class library Iterator methods: hasNext – returns true if there are more elements in the iteration next – returns the next element in the iteration

Copyright © 2004 Pearson Addison-Wesley. All rights reserved.1-19 Bag Exceptions Collections must always manage problem situations carefully For example: attempting to remove an element from an empty bag The designer of the collection determines how it might be handled Our implementation provides an isEmpty method, so the user can check beforehand And it throws an exception if the situation arises, which the user can catch

Copyright © 2004 Pearson Addison-Wesley. All rights reserved.1-20 Using a Bag: BINGO The game of BINGO can be used to demonstrate the use of a bag collection Each player has a bingo card with numeric values associated with the letters B-I-N-G-O Letter/number combinations (on bingo balls) are picked at random, which the player marks on their card if possible The first player to get five squares in a row wins

Copyright © 2004 Pearson Addison-Wesley. All rights reserved.1-21 figure 2.6 A bingo card

Copyright © 2004 Pearson Addison-Wesley. All rights reserved.1-22 BINGO A bag is an appropriate collection for BINGO, allowing the caller to pick numbers at random We create an object of class BingoBall to represent one letter/number combination See BingoBall.java (page 42)BingoBall.java The main program creates the balls, stores them in a bag, and draws them at random See Bingo.java (page 43)Bingo.java

Copyright © 2004 Pearson Addison-Wesley. All rights reserved.1-23 BINGO Note that the class that represents the bag is called ArrayBag Any implementation of a bag collection could have been used at that point The object returned from the removeRandom method is cast into a BingoBall because the collection stores generic Object objects

Copyright © 2004 Pearson Addison-Wesley. All rights reserved.1-24 figure 2.7 UML description of the Bingo and BingoBall classes

Copyright © 2004 Pearson Addison-Wesley. All rights reserved.1-25 Implementing a Bag The discussion of the BINGO game used a bag collection without any regard to how that collection was implemented We were using the bag collection for its functionality – how it is implemented is fundamentally irrelevant It could be implemented in various ways Let's examine how we can use an array to implement it

Copyright © 2004 Pearson Addison-Wesley. All rights reserved.1-26 figure 2.8 An array of object references

Copyright © 2004 Pearson Addison-Wesley. All rights reserved.1-27 Managing Capacity An array has a particular number of cells when it is created – its capacity So the array's capacity is also the bag's capacity What do we do when the bag is full and a new element is added? We could throw an exception We could return some kind of status indicator We could automatically expand the capacity

Copyright © 2004 Pearson Addison-Wesley. All rights reserved.1-28 Managing Capacity The first two options require the user of the collection to be on guard and deal with the situation as needed The third option is best, especially in light of our desire to separate the implementation from the interface The capacity is an implementation problem, and shouldn't be passed along to the user unless there is a good reason to do so

Copyright © 2004 Pearson Addison-Wesley. All rights reserved.1-29 The ArrayBag Class In the Java Collections API, class names indicate both the underlying data structure and the collection We adopt the same naming convention Thus, the ArrayBag class represents an array implementation of a bag collection Bag elements are kept contiguously at one end of the array An integer ( count ) represents: the number of elements in the bag the next empty index in the array

Copyright © 2004 Pearson Addison-Wesley. All rights reserved.1-30 figure 2.9 An array implementation of a bag

Copyright © 2004 Pearson Addison-Wesley. All rights reserved.1-31 ArrayBag Constructors // // Creates an empty bag using the specified capacity. // public ArrayBag (int initialCapacity) { count = 0; contents = new Object[initialCapacity]; } // // Creates an empty bag using the default capacity. // public ArrayBag() { count = 0; contents = new Object[DEFAULT_CAPACITY]; }

Copyright © 2004 Pearson Addison-Wesley. All rights reserved.1-32 size and isEmpty Operations // // Returns true if this bag is empty and false otherwise. // public boolean isEmpty() { return (count == 0); } // // Returns the number of elements currently in this bag. // public int size() { return count; }

Copyright © 2004 Pearson Addison-Wesley. All rights reserved.1-33 The add Operation // // Adds the specified element to the bag, expanding the capacity // of the bag array if necessary. // public void add (Object element) { if (size() == contents.length) expandCapacity(); contents[count] = element; count++; }

Copyright © 2004 Pearson Addison-Wesley. All rights reserved.1-34 The expandCapacity Method // // Creates a new array to store the contents of the bag with // twice the capacity of the old one. // private void expandCapacity() { Object[] larger = new Object[contents.length*2]; for (int index=0; index < contents.length; index++) larger[index] = contents[index]; contents = larger; }

Copyright © 2004 Pearson Addison-Wesley. All rights reserved.1-35 The addAll Operation // // Adds the contents of the parameter to this bag. // public void addAll (BagADT bag) { Iterator scan = bag.iterator(); while (scan.hasNext()) add (scan.next()); }

Copyright © 2004 Pearson Addison-Wesley. All rights reserved.1-36 The removeRandom Operation // // Removes a random element from the bag and returns it. Throws // an EmptyBagException if the bag is empty. // public Object removeRandom() throws EmptyBagException { if (isEmpty()) throw new EmptyBagException(); int choice = rand.nextInt(count); Object result = contents[choice]; contents[choice] = contents[count-1]; // fill the gap contents[count-1] = null; count--; return result; }

Copyright © 2004 Pearson Addison-Wesley. All rights reserved.1-37 The remove Operation // // Removes one occurance of the specified element from the bag // and returns it. Throws an EmptyBagException if the bag is // empty and a NoSuchElemetnException if the target is not in // the bag. // public Object remove (Object target) throws EmptyBagException, NoSuchElementException { int search = NOT_FOUND; if (isEmpty()) throw new EmptyBagException(); for (int index=0; index < count && search == NOT_FOUND; index++) if (contents[index].equals(target) search = index;

Copyright © 2004 Pearson Addison-Wesley. All rights reserved.1-38 remove continued if (search == NOT_FOUND) throw new NoSuchElementException(); Object result = contents[search]; contents[search] = contents[count-1]; contents[count-1] = null; count--; return result; }

Copyright © 2004 Pearson Addison-Wesley. All rights reserved.1-39 The union Operation // // Returns a new bag that is the union of this bag and the // parameter. // public BagADT union (BagADT bag) { ArrayBag both = new ArrayBag(); for (int index = 0; index < count; index++) both.add (contents[index]); Iterator scan = bag.iterator(); while (scan.hasNext()) both.add (scan.next()); return both; }

Copyright © 2004 Pearson Addison-Wesley. All rights reserved.1-40 The contains Operation // // Returns true if this bag contains the specified target // element. // public boolean contains (Object target) { int search = NOT_FOUND; for (int index=0; index < count && search == NOT_FOUND; index++) if (contents[index].equals(target) search = index; return (search == NOT_FOUND); }

Copyright © 2004 Pearson Addison-Wesley. All rights reserved.1-41 The equals Operation // // Returns true if this bag contains exactly the same elements // as the parameter. // public boolean equals (BagADT bag) { boolean result = false; ArrayBag temp1 = new ArrayBag(); ArrayBag temp2 = new ArrayBag(); Object obj; if (size() ++ bag.size()) { temp1.addAll(this); temp2.addAll(bag); Iterator scan = bag.iterator();

Copyright © 2004 Pearson Addison-Wesley. All rights reserved.1-42 equals continued while (scan.hasNext()) { obj = scan.next(); if (temp1.contains(obj)) { temp1.remove(obj); temp2.remove(obj); } result = (temp1.isEmpty() && temp2.isEmpty()); } return result; }

Copyright © 2004 Pearson Addison-Wesley. All rights reserved.1-43 The iterator Operation // // Returns an iterator for the elements currently in this bag. // public Iterator iterator() { return new ArrayIterator (contents, count); } See ArrayIterator.java (page 58)ArrayIterator.java

Copyright © 2004 Pearson Addison-Wesley. All rights reserved.1-44 The toString Operation // // Returns a string representation of this bag. // public String toString() { String result = ""; for (int index=0; index < count; index++) result = result + contents[index].toString() + "\n"; return result; }

Copyright © 2004 Pearson Addison-Wesley. All rights reserved.1-45 figure 2.10 UML description of the bingo system

Copyright © 2004 Pearson Addison-Wesley. All rights reserved.1-46 Analysis of ArrayBag If the array is not full, adding an element to the bag is O(1) Expanding the capacity is O(n) Removing a particular element, because it must be found, is O(n) Removing a random element is O(1) Adding all elements of another bag is O(n) The union of two bags is O(n+m), where m is the size of the second bag