Collections COMP 103 #3 2008T2.

Slides:



Advertisements
Similar presentations
Why not just use Arrays? Java ArrayLists.
Advertisements

CSC 205 – Java Programming II Lecture 25 March 8, 2002.
CSE 143 Lecture 22: Advanced List Implementation (ADTs; interfaces; abstract classes; inner classes; generics; iterators)
TCSS 342, Winter 2005 Lecture Notes
Building Java Programs
CSE373 Optional Section Java Collections 11/12/2013 Luyi Lu.
Information and Computer Sciences University of Hawaii, Manoa
Lists Ellen Walker CPSC 201 Data Structures Hiram College.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington2012 More Collections: Queues,
Some Other Collections: Bags, Sets, Queues and Maps COMP T2 Lecture 4 School of Engineering and Computer Science, Victoria University of Wellington.
ArrayList Class An ArrayList is an object that contains a sequence of elements that are ordered by position. An ArrayList is an object that contains a.
Stacks and Queues. 2 3 Runtime Efficiency efficiency: measure of computing resources used by code. can be relative to speed (time), memory (space), etc.
2013-T2 Lecture 18 School of Engineering and Computer Science, Victoria University of Wellington  Marcus Frean, Lindsay Groves, Peter Andreae, and John.
Interfaces, Classes, Collections School of Engineering and Computer Science, Victoria University of Wellington COMP T2 Lecture 3 Thomas Kuehne.
1 Stacks (Continued) and Queues Array Stack Implementation Linked Stack Implementation The java.util.Stack class Queue Abstract Data Type (ADT) Queue ADT.
Week 2 - Friday.  What did we talk about last time?  Computing Big Oh.
CSE 373: Data Structures and Algorithms Lecture 2: Queues.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington ArrayLists: varying size arrays.
Some Other Collections: Bags, Sets, Queues and Maps COMP T2 Lecture 4 School of Engineering and Computer Science, Victoria University of Wellington.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington ArrayLists: varying size arrays.
Interfaces, Classes, Collections School of Engineering and Computer Science, Victoria University of Wellington COMP T2 Lecture 3 Marcus Frean.
Copyright © Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java From Control Structures through Data Structures by Tony.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Chapter 18 List ADT Animated Version.
2015-T2 Lecture 19 School of Engineering and Computer Science, Victoria University of Wellington  Marcus Frean, Lindsay Groves, Peter Andreae, and John.
COMP 103 Maps and Queues. RECAP  Iterators (for-each loop)  Bag, Sets, and Stacks - a class, not interface TODAY  Maps and Queues 2 RECAP-TODAY QUICK.
1 CS162: Introduction to Computer Science II Abstract Data Types.
Stacks and Queues. 2 Abstract Data Types (ADTs) abstract data type (ADT): A specification of a collection of data and the operations that can be performed.
Interfaces, Classes, Collections School of Engineering and Computer Science, Victoria University of Wellington COMP T2 Lecture 3 Thomas Kuehne.
An Array-Based Implementation of the ADT List
Using the Java Collection Libraries COMP 103 # T2
Building Java Programs
Some Collections: BAGS, SETS, and STACKS
Stacks and Queues.
(like an array on steroids)
Heaps And Priority Queues
CSE 373: Data Structures and Algorithms
COP 3503 FALL 2012 Shayan Javed Lecture 8
A tree set Our SearchTree class is essentially a set.
Stacks and Queues.
COMP 103 Maps, Stacks Thomas Kuehne 2016-T2 Lecture 5
Building Java Programs
Data Structures 1 1.
Top Ten Words that Almost Rhyme with “Peas”
Preconditions precondition: Something your method assumes is true at the start of its execution. Often documented as a comment on the method's header:
Week 2: 10/1-10/5 Monday Tuesday Wednesday Thursday Friday
HW-6 Deadline Extended to April 27th
Welcome to CSE 143!.
Queues, Deques and Priority Queues
Queues, Deques and Priority Queues
TCSS 143, Autumn 2004 Lecture Notes
Stacks and Queues.
Words exercise Write code to read a file and display its words in reverse order. A solution that uses an array: String[] allWords = new String[1000]; int.
A tree set Our SearchTree class is essentially a set.
Building Java Programs
Chapter 10 ArrayList reading: 10.1
CSE 143 Lecture 2 Collections and ArrayIntList
Welcome to CSE 143!.
Queues 12/30/2018 9:24 PM Queues 12/30/2018 9:24 PM Queues.
Stacks and Queues CLRS, Section 10.1.
Grouped Data Arrays, and Array Lists.
ArrayLists 22-Feb-19.
slides created by Marty Stepp
Generics, Lambdas, Reflections
Review of Previous Lesson
slides created by Alyssa Harding
Review: libraries and packages
Generics, Stack, Queue Based on slides by Alyssa Harding
CSE 143 Lecture 21 Advanced List Implementation
Stacks and Queues.
Presentation transcript:

Collections COMP 103 #3 2008T2

Menu Using List and ArrayList Using Queues Administrivia: tutorials (sign up at https://signups.victoria.ac.nz/help desks, assignments We will need to do some rearranging Start next week Testing your CardSorter: start with a small deck – eg, just the first three ranks: 1-3

Comments on code style for 103 I will drop “this.” except when needed. instead of this.loadFromFile(fname) just loadFromFile(fname) instead of this.shapes.addShape(shape) just shapes.addShape(shape) I may leave out { } when surrounding just one statement instead of while (i < name.length) { name[i] = null; } just while (i < name.length) name[i] = null;

Methods on Collection and List Collection <E> isEmpty() → boolean size() → int contains(E elem) → boolean add(E elem) → boolean (whether it succeeded) remove(E elem) → boolean (whether it removed an item) iterator() → iterator <E> … List <E> add(int index, E elem) remove(int index) → E (returns the item removed) get(int index) → E set(int index, E elem) → E (returns the item replaced) indexOf(E elem) → int subList(int from, int to) → List<E> Methods on all types of collections Additional methods on all Lists

Example TodoList – collection of tasks, in order they should be done. Collection type: List of tasks Requirements of TodoList: read list of tasks from a file, display all the tasks add task, at end, or at specified position remove task, move task to a different position.

Example (TodoList program) public class TodoList implements UIButtonListener{ : private List<Task> tasks; /* read list of tasks from a file, */ public void readTasks(String fname){ tasks = new ArrayList<Task>(); try { Scanner sc = new Scanner(new File(fname)); while ( sc.hasNext() )  { String line = sc.nextLine(); tasks.add(new Task(line)); } sc.close(); } catch(IOException e){…} displayTasks(); Abstract type: List Concrete type: ArrayList

Iterating through List: public void displayTasks(){ textArea.setText(tasks.size() +“ tasks to be done:\n”); for (Task task : tasks){ textArea.append(task + "\n"); } Or for (int i=0; i<tasks.size(); i++) textArea.append(tasks.get(i) + "\n"); Iterator <Task> iter = tasks.iterator(); while (iter.hasNext()){ textArea.append(iter.next() + "\n"); Automatically calls toString() method

More of the TodoList example: public void buttonPerformed(String button){ if ( button .equals("Add") ) tasks.add(askTask()); else if (button.equals("Remove") ) tasks.remove(askTask()); else if (button.equals( "AddAt" ) ) tasks.add(UI.askInt("add at position: "), askTask()); else if (button.equals("RemoveFrom") ) tasks.remove(UI.askInt("from position: ")); else if (button.equals("MoveTo") ){ int from= UI.askInt(“move from position: "); int to = UI.askInt(“move to position: ") tasks.add(to, tasks.remove(from)); displayTasks(); } Task task= tasks.get(from); tasks.remove(from); tasks.add(to, task);

List vs Array Lists are nicer than arrays: No size limit!!! They grow bigger as necessary Lots of code written for you: jobList.set(ind, value) jobArray[ind] = value jobList.get(ind) jobArray[ind] jobList.size() ? (Not the length!!!) jobList.add(value) ? (Where is the end? What if full?) jobList.add(ind, value) ? (Have to shift everything up!!!) jobList.remove(ind) ? (Have to shift everything down!!!) jobList.remove(value) ? (Have to find value, then shift things down!!!) for (Task t : tasks) or for( int i = 0; i< ???; i++){ for( int i = 0; i< tasks.size(); i++){ Task t = taskArray[ i ]; Task t = task(i);

What can you put in a collection? The type parameter of a collection can be any object type. private List <Face> faces = new ArrayList <Face>(); public void processStrings(Set<String> strings){… Stack<XMLTag> tags = new Stack<XMLTag>(); Set < List <Task> > allJobs = new HashSet< List <Task>>(); What about collections of numbers, or booleans, or chars… private List<int> myNums = new ArrayList<int>(); public int computeScore(List<boolean> answers){…. Must use “wrapper classes”: Integer, Boolean, Double, Char, etc private List<Integer> myNums = new ArrayList<Integer>(); public int computeScore(List<Boolean> answers){….

Collections of primitive types You can wrap a primitive type into a wrapper object: List<Integer> myNums = new ArrayList<Integer>(); Integer num = new Integer(15); myNums.add(num); You can extract a primitive type from a wrapper object: int sum = 0; for (Integer num : myNums){ int n = num.intValue(); sum = sum + n; } But this is just a pain! Could write own classes for collections of integers, and of doubles, and of booleans,….

Autoboxing But Java will do it automatically for you (most of the time!) private List<Integer> myNums = new ArrayList<Integer>(); myNums.add(15); int sum = 0; for (Integer num : myNums){ sum = sum + num; } Or for (int num : myNums){ Autoboxes a primitive type if wrapper type expected Auto-unboxes a wrapper type when primitive type expected.

Queues Queues are like Stacks Collection of values with an order Constrained access: Only remove from the front Two varieties: Ordinary queues: only add at the back Priority queues: add with a given priority

Queues Used for Java provides Operating Systems, Network Applications, multi-user systems Handling requests/events/jobs that must be done in order (often called a “buffer” in this context) Simulation programs Representing queues in the real world (traffic, customers, deliveries, ….) Managing the events that must happen in the future Search Algorithms Computer Games Artificial Intelligence Java provides a Queue interface several classes: LinkedList, PriorityQueue, ….

Queue Operations offer(value) ⇒ boolean (sometimes called “enqueue” ) add a value to the queue poll() ⇒ value (sometimes called “dequeue” ) remove and return value at front/head of queue or null if the queue is empty peek() ⇒ value return value at head of queue, or null if queue is empty (doesn’t remove from queue) remove() and element() like poll() and peek(), but throw exception if queue is empty. and all the Collection operations Why use Queue instead of List?? Efficiency: you can make queues that are very efficient for the constrained access actions, but would not be efficient for general list operations. Clarity: By declaring it as a queue, you make it clear to other programmers reading/modifying your code what this collection is for and how it should be used. Error prevention: The compiler will stop you from doing illegal operations on a Queue, whereas, if it were a list, you might write them by mistake. Note: if you need to be able to access the middle of the queue, and mess with it, then you will need to use a list.

A Queue Example. Simulation of a bank with two teller queues: want to see how it will cope with various client loads: how big might the queues get? assume that each client will go to the shortest queue What do we care about? How often a new client turns up. Probability of arriving How long a client will take at the teller Represent client by number of timesteps they will take.

A Queue Example. public void simulate(int serveTime, double probArrival){ int t1 = 0; // how many time steps will the teller be busy int t2 = 0; Queue <Integer> q1 = new LinkedList <Integer>(); Queue <Integer> q2 = new LinkedList <Integer>(); for (int time =0; time< MaxTime; time++){ if ( Math.random()< probArrival) { int client = (int) (Math.random()*serveTime); if ( q1.size()<q2.size() ) q1.offer(client); else q2.offer(client); } if ( t1==0 && !q1.isEmpty() ) t1 = q1.poll(); if ( t2==0 && !q2.isEmpty() ) t2 = q2.poll(); if (t1 > 0) t1--; if (t2 > 0) t2--; UI.printf("queues: %d %d /n", q1.size() , q2.size()); }}