Download presentation
Presentation is loading. Please wait.
1
Collections COMP 103 #3 2008T2
2
Menu Using List and ArrayList Using Queues Administrivia:
tutorials (sign up at 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
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;
4
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
5
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.
6
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
7
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
8
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);
9
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);
10
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){….
11
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,….
12
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.
13
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
14
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, ….
15
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.
16
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.
17
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()); }}
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.