+ All Categories
Home > Documents > Lecture 10: Finishing Off. Overview Stacks, Queues, Lists Generics More about Exceptions Sorting...

Lecture 10: Finishing Off. Overview Stacks, Queues, Lists Generics More about Exceptions Sorting...

Date post: 29-Jan-2016
Category:
Upload: magdalene-elaine-white
View: 213 times
Download: 0 times
Share this document with a friend
54
CSCI1227 Computer Programming and Problem Solving Lecture 10: Finishing Off
Transcript

Slide 1

CSCI1227Computer Programming andProblem Solving Lecture 10: Finishing OffOverviewStacks, Queues, ListsGenericsMore about ExceptionsSorting TechniquesA StackA stack is an ADT designed to store valuesIt functions like a tray dispenser in a cafeteriaLIFO: Last in, First out take from the top of the stackFILO: First in, Last out stuff gets pushed to the bottomStacks have two main interface methods:push(): add something to the top of the stackpop(): take something off of the stackAn Integer Stack ADTpublic class stack { private int tos; // Top of stack private int[] data; // The pile of integers we store public stack (int size) { // Constructor data = new int[size]; tos = 0; } public void push(int val) { // Interface method to add item data[tos++] = val; } public int pop () { // Interface method to remove item return (data[--tos]); }} // end class stackQueuesA Queue is an ADT that functions like a bank line-up. Where a stack was FILO (first in, last out), a queue is FIFO (first in, first out)Instead of push() and pop(), the interface methods are enqueue() and dequeue()We usually implement a queue using a "circular array"That is, when we hit the back of the array, we wrap around and back to the front of the arrayUse two variables:Index of the front of the queue (next to remove)Index of the back of the queue (where to add next item)ExerciseImplement a queue given the following interface:

public interface FIFO { public void enqueue(int val) throws Exception; public int dequeue() throws Exception; public int count(); }

count returns the number of items currently in the queue.Add a constructor that initialises an empty queue to a provided size (Note: interfaces in Java can't contain constructors). Solutionpublic class queue implements FIFO {public int count() { private int numItems, head, tail; return (numItems); private int[] data;} public void enqueue(int val) throws Exception {public queue (int size) { if (numItems == data.length) data = new int[size]; throw new Exception ("Overflow"); head = 0; tail = 0; data[tail++] = val; numItems = 0; numItems += 1;} tail = tail % data.length; }

public int dequeue() throws Exception { int v; if (numItems == 0) throw new Exception ("Underflow"); v = data[head++]; head = head % data.length; numItems -= 1; return (v); }

} // end class queueListsArrays are fixed length if we want to change the size we make a new array of the correct size and copy the values from the old arrayLists are a variable length data structure that adjusts to hold more or less as requiredJava provides a class called ArrayList (Ch. 12) for when we want variable length arrays Also, when we defined our stack, we defined it for int, we would need a different version for StringArrayLists can be created for ANY class typeNew Syntax!Optional (Ch. 12) Not responsible for this on examOnly works for classes/objects, not for primitive types like int, double (uses inclusion polymorphism)ArrayList myList = new ArrayList();Note: Second "String" is optional in Java 7.0+E.g., ArrayList myList = new ArrayList();See Fig 12.1 for listing of class methodsUsing a List A Stackimport java.util.ArrayList;

public class stack2 { private ArrayList data;

public stack2 () { // Constructor data = new ArrayList(); }

public void push(String val) { data.add(0, val); // add as index value 0 } public String pop () { return (data.remove(0)); // remove index value 0 }} // end class stack2Using a List A Queueimport java.util.ArrayList;

public class queue2 { private ArrayList data;

public queue2 () { // Constructor data = new ArrayList(); } public void enqueue(String val) { data.add(val); } public String dequeue () { return (data.remove(0)); } public int count () { return data.size(); }} // end class queue2Exploiting PolymorphismTo really improve our queue, lets just store ObjectsEVERY class is a descendent of Object in Java, so we can store any class in the queueUse wrapper classes (e.g., Integer for int) to store primitive typesA Polymorphic Queueimport java.util.ArrayList;

public class polyqueue { private ArrayList data;

public polyqueue () { // Constructor data = new ArrayList(); } public void enqueue(String val) { data.add(val); } public void enqueue(int val) { data.add(new Integer(val)); } public String sDequeue () { return ((String) data.remove(0)); } public int iDequeue() { return(((Integer) data.remove(0)).intValue()); } public int count () { return data.size(); }} // end class polyqueueUsing our polyqueuepublic class driver { public static void main (String[] a) { polyqueue q = new queue(); q.enqueue("Hello"); q.enqueue("world"); System.out.printf("%s %s!\n", q.sDequeue(), q.sDequeue()); q.enqueue(7); q.enqueue(3); System.out.printf("7 + 3 = %d\n", (q.iDequeue() + q.iDequeue())); } // end main()} // end class driverGenerics (Section 12.4)A generic class is a parameterised classWhen we instantiate ArrayList, we have to specify what type we wish to instantiate it forWe say that an ArrayList has a type as its parameterWe can parameterise any class that we will want to make different versions for different typesThe types must always be objectsWe can use wrapper classes when we want to store int, double, etc.An Examplepublic class Pair { private type v1, v2; public void setFirst (type value) { v1 = value; } public void setSecond(type value) { v2 = value; } public type first() { return (v1); } public type second() { return (v2); }} // end class Pair Using a GenericWe provide a type when we instantiate the class to create an objectThe object we get is specialised for the type we give itPair ip = new Pair();Pair sp = new Pair();ExerciseA integer is prime if it is greater than 1 and its only divisors are 1 and itself. That is, a number, n, cannot be evenly divided (no remainder) by any 1 < value < n.Write a method called isPrime(int n) that returns true if n is prime and false otherwise. Solutionpublic boolean isPrime (int n) { int root = (int) Math.sqrt(n); for (int i = 2; i pivotThe Code Part 1public static int[] qsort (int[] values) { // Check for null, empty, or singleton array if ((values == null) || (values.length


Recommended