Chapter 3 Collection Classes Anshuman Razdan Department of Engineering

Slides:



Advertisements
Similar presentations
Queues Printer queues Several jobs submitted to printer Jobs form a queue Jobs processed in same order as they were received.
Advertisements

Why not just use Arrays? Java ArrayLists.
Linked Lists Linear collections.
COSC 1P03 Data Structures and Abstraction 9.1 The Queue Whenever you are asked if you can do a job, tell 'em, "Certainly, I can!" Then get busy and find.
Written by: Dr. JJ Shepherd
Stacks, Queues, and Deques. 2 A stack is a last in, first out (LIFO) data structure Items are removed from a stack in the reverse order from the way they.
queues1 Queues Data structures that wait their turn.
Chapter 7 Queues. Data Structure 2 Chapter Outline  Objectives  Follow and explain queue-based algorithms using the front, rear, entering the queue,
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.
Lecture 23 Input and output with files –(Sections 2.13, 8.7, 8.8) Exceptions and exception handling –(Chapter 17)
Designing an ADT The design of an ADT should evolve naturally during the problem-solving process Questions to ask when designing an ADT What data does.
CSC 205 – Java Programming II Lecture 25 March 8, 2002.
An Array-Based Implementation of the ADT List public class ListArrayBased implements ListInterface { private static final int MAX_LIST = 50; private Object.
Arrays An array is a collection of variables, all of the same type. An array is created with the new operator. The size of an array must be specified at.
Stacks1 Stacks The unorganized person’s data structure.
Razdan with contribution from others 1 Chapter 7 Queues Anshuman Razdan Div of Computing Studies
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.
hashing1 Hashing It’s not just for breakfast anymore!
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.
Part-B1 Stacks. Stacks2 Abstract Data Types (ADTs) An abstract data type (ADT) is an abstraction of a data structure An ADT specifies: Data stored Operations.
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.
CST Razdan et al Razdan with contribution from others 1 Chapter 6 Stacks Anshuman Razdan Div of Computing.
Linklist21 Linked Lists II The rest of the story.
Chapter 4 Linked Lists Anshuman Razdan Div of Computing Studies
Stacks, Queues, and Deques
Topic 3 The Stack ADT.
Chapter 3 Introduction to Collections – Stacks Modified
Chapter 6 Array-Based Lists.
Lists Ellen Walker CPSC 201 Data Structures Hiram College.
EECE 310: Software Engineering Iteration Abstraction.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
© 2004 Goodrich, Tamassia Stacks. © 2004 Goodrich, Tamassia Stacks2 Abstract Data Types (ADTs) An abstract data type (ADT) is an abstraction of a data.
IMPLEMENTING ARRAYLIST – Part 2 COMP 103. RECAP  Abstract Classes – overview, details in 2 nd year  Implementing the ArrayList: size(), get(), set()
1/20/03A2-1 CS494 Interfaces and Collection in Java.
Arrays Construct array: new double[10] Store in variable of type double[] double[] data = new double[10];
 A Collection class is a data type that is capable of holding a group of items.  In Java, Collection classes can be implemented as a class, along with.
CHAPTER 5 ArrayLists.
Generic Programming  Object Type  Autoboxing  Bag of Objects  JCL Collections  Nodes of Objects  Iterators.
Information and Computer Sciences University of Hawaii, Manoa
HashCode() 1  if you override equals() you must override hashCode()  otherwise, the hashed containers won't work properly  recall that we did not override.
Chapter 11 Hash Anshuman Razdan Div of Computing Studies
Chapter 2 Collections. Copyright © 2004 Pearson Addison-Wesley. All rights reserved.1-2 Chapter Objectives Define the concept and terminology related.
Genericity collections of objects. COSC 2006 Bags of Objects2 collections of objects  for real programming applications, pratical collections are collections.
Chapter 3 Collections. Objectives  Define the concepts and terminology related to collections  Explore the basic structures of the Java Collections.
CS 367 Introduction to Data Structures Lecture 2 Audio for Lecture 1 is available Homework 1 due Friday, September 18.
TreeBag a BST implementation. Example class - TreeBag  remember Bag?  collection of items, order does not matter  repeated items allowed public void.
Chapter 7 Queues Introduction Queue applications Implementations.
CSE 143 Lecture 4 More ArrayIntList : Pre/postconditions; exceptions; testing reading: slides created by Marty Stepp and Hélène Martin
Lecture 8: Advanced OOP Part 2. Overview Review of Subtypes Interfaces Packages Sorting.
IMPLEMENTING ARRAYLIST COMP 103. RECAP  Comparator and Comparable  Brief look at Exceptions TODAY  Abstract Classes - but note that the details are.
Puzzle 2 1  what does the following program print? public class Puzzle02 { public static void main(String[] args) { final long MICROS_PER_DAY = 24 * 60.
© 2010 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of CHAPTER 15: Sets and Maps Java Software Structures: Designing and Using.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Chapter 18 List ADT Animated Version.
“The desire for safety stands against every great and noble enterprise.” – Tacitus Thought for the Day.
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 The copy constructor in the BankAccounts class. Two alternatives here: /** copy constructor */ public BankAccounts(BankAccounts L){ theAccounts = L.theAccounts.clone();
Implementing ArrayList Part T2 Lecture 6 School of Engineering and Computer Science, Victoria University of Wellington  Thomas Kuehne, Marcus Frean,
1 Stacks Abstract Data Types (ADTs) Stacks Application to the analysis of a time series Java implementation of a stack Interfaces and exceptions.
An Array-Based Implementation of the ADT List
Stacks.
Collection Classes A Collection class is a data type that is capable of holding a group of items. In Java, Collection classes can be implemented as a class,
Implementing ArrayList Part 1
null, true, and false are also reserved.
Programming in Java Lecture 11: ArrayList
Chapter 6 Array-Based Lists.
Collections Framework
Collision Handling Collisions occur when different elements are mapped to the same cell.
Stacks, Queues, and Deques
Presentation transcript:

Chapter 3 Collection Classes Anshuman Razdan Department of Engineering

CET Razdan with contribution from others 2 Collection Classes Collection Class – an ADT in which each object contains a number of elements. –Bag – a container that holds an unordered collection of elements –Sequence – a container that holds an ordered collection of elements

CET Razdan with contribution from others 3 Bag ADT Specification Constructor(s) – can specify capacity of bag Add – put something in the bag Remove – take something out of the bag Size – tells how many things in the bag ensureCapacity – make sure the bag can hold a given number of items trimToSize – make the capacity of the bag exactly the number of items currently in the bag countOccurrences – counts how many of a given item are in the bag addAll – dump one bag into another Union – create new bag with same contents as two other bags Clone – returns a “copy” of a bag

CET Razdan with contribution from others 4 Review Arrays Arrays are Java objects –int[] nums = new int[4]; –int[] nums = new int[] {1,2,3,72}; The length attribute (NOT method) tells the number of indices in the array Arrays have a clone method that will return a “copy” (clone) of the array.

CET Razdan with contribution from others 5 Implementing a clone method The purpose of a clone method is to create a copy of an object Cloneable is a java interface. If we want to implement a clone method: –Modify class head to public class MyClass implements Cloneable –Use super.clone to make a copy using clone of “parent” –Add any additional implementation to make copy

CET Razdan with contribution from others 6 Generic clone method The clone method should follow a format similar to (see page 85 of textbook): public Object clone(){ MyObject answer; try{ answer = (MyObject) super.clone(): } catch( CloneNotSupportedException e ){ throw new RuntimeException (“This class does not implement Cloneable.”); } // any additional code for making a copy return answer; }

CET Razdan with contribution from others 7 IntArrayBag Class Public class IntArrayBag implements Cloneable { private int[] data; // array to store collection // of integers private int manyItems; // current capacity of bag // public methods }

CET Razdan with contribution from others 8 Constructors public IntArrayBag( ) { final int INITIAL_CAPACITY = 10; manyItems = 0; data = new int[INITIAL_CAPACITY]; } public IntArrayBag(int initialCapacity) { if (initialCapacity < 0) throw new IllegalArgumentException ("The initialCapacity is negative: " + initialCapacity); data = new int[initialCapacity]; manyItems = 0; }

CET Razdan with contribution from others 9 Add method public void add(int element) { if (manyItems == data.length) { // Double the capacity and add 1; this works even if manyItems is 0. // However, in the case that manyItems*2 + 1 is beyond // Integer.MAX_VALUE, there will be an arithmetic overflow and // the bag will fail. ensureCapacity(manyItems*2 + 1); // why do we have } // to do this???? data[manyItems] = element; manyItems++; }

CET Razdan with contribution from others 10 Remove method public boolean remove(int target) { int index; // The location of target in the data array. // First, set index to location of target in data array, which could be as small // as 0 or as large as manyItems-1; If target is not in array, index will be manyItems; for (index = 0; (index < manyItems) && (target != data[index]); index++) // No work is needed in the body of this for-loop. ; if (index == manyItems) // target not found, so nothing is removed. return false; else { // target found at data[index]; reduce manyItems and copy last element onto data[index]. manyItems--; data[index] = data[manyItems]; return true; }

CET Razdan with contribution from others 11 countOccurrences method public int countOccurrences(int target) { int answer; int index; answer = 0; for (index = 0; index < manyItems; index++) if (target == data[index]) answer++; return answer; }

CET Razdan with contribution from others 12 addAll method public void addAll(IntArrayBag addend) { // If addend is null, then a NullPointerException is thrown. // In the case that the total number of items is beyond // Integer.MAX_VALUE, there will be an arithmetic overflow and // the bag will fail. ensureCapacity(manyItems + addend.manyItems); System.arraycopy(addend.data, 0, data, manyItems, addend.manyItems); manyItems += addend.manyItems; } Copy from array Starting at indexCopy to array Starting at index Copy this many elements

CET Razdan with contribution from others 13 Union method public static IntArrayBag union(IntArrayBag b1, IntArrayBag b2) { // If either b1 or b2 is null, then a NullPointerException is thrown. // In the case that the total number of items is beyond // Integer.MAX_VALUE, there will be an arithmetic overflow and // the bag will fail. IntArrayBag answer = new IntArrayBag(b1.getCapacity( ) + b2.getCapacity( )); System.arraycopy(b1.data, 0, answer.data, 0, b1.manyItems); System.arraycopy(b2.data, 0, answer.data, b1.manyItems, b2.manyItems); answer.manyItems = b1.manyItems + b2.manyItems; return answer; }

CET Razdan with contribution from others 14 Clone method public Object clone( ) { // Clone a IntArrayBag object. IntArrayBag answer; try { answer = (IntArrayBag) super.clone( ); } catch (CloneNotSupportedException e) { throw new RuntimeException ("This class does not implement Cloneable"); } answer.data = (int [ ]) data.clone( ); // why do we have return answer; // to do this???? }

CET Razdan with contribution from others 15 ensureCapacity method public void ensureCapacity(int minimumCapacity) { int biggerArray[ ]; if (data.length < minimumCapacity) { biggerArray = new int[minimumCapacity]; System.arraycopy(data, 0, biggerArray, 0, manyItems); data = biggerArray; } Why not initialize earlier???

CET Razdan with contribution from others 16 trimToSize method public void trimToSize( ) { int trimmedArray[ ]; if (data.length != manyItems) { trimmedArray = new int[manyItems]; System.arraycopy(data, 0, trimmedArray, 0, manyItems); data = trimmedArray; }

CET Razdan with contribution from others 17 getCapacity method public int getCapacity( ) { return data.length; } size method public int size( ) { return manyItems; }

CET Razdan with contribution from others 18 Complexity Analysis Determine run-time for each Bag method, assume the following: –Bag b1 has n1 elements & capacity c1 –Bag b2 has n2 elements & capacity c2 –Methods operating on a single bag, write in terms of b1 –Methods operating on two bags, use both b1 and b2

CET Razdan with contribution from others 19 Complexity (At Home) MethodTime AnalysisMethodTime Analysis Constructor (0 param) Constructor (1 param) addaddAll unionremove countOccurrencesclone sizegetCapacity ensureCapacitytrimToSize