1CMSC 131 Fall 2007Jan Plane (adapted from Bonnie Dorr)Lecture 26:CollectionsLast time:1.ExceptionsToday1.Collections : StackCMSC 131 Fall 2007Jan Plane (adapted from Bonnie Dorr)1Collections in JavaArrays are collectionsArrays are objectsArrays are sequences of elements in base typeThese elements are collected together in one object: the arrayJava includes may other collection mechanismsArrays good for some applications (fixed-length sequences), not others (varying-length sequences)Other collections tuned for different purposesGeneral observation holds, however:Collections are objects …… that contain other objects in a given typeWe’ll study two (more in CMSC132): Stack, ArrayListCMSC 131 Fall 2007Jan Plane (adapted from Bonnie Dorr)2Stacks in JavaRecall: a stack is a data structure (“device”for holding values) – FILO (First In, Last Out)Typical operations on a stackpush: add a new value into the stackpop: remove the most recently added value still in stacktop: return the most recently added value in stackNote: Java calls this “peek”is empty: returns true if the stack is currently empty or false otherwise2CMSC 131 Fall 2007Jan Plane (adapted from Bonnie Dorr)3Example of stack concept (not Java specific)Stack s s.isempty() == ??true s.push (3);s.isempty() == ??false s.push (4);s.peek == ??4s.pop ();s.push (5);s.peek == ??5s345CMSC 131 Fall 2007Jan Plane (adapted from Bonnie Dorr)4Stacks in Java (cont.)Java includes a generic class for stack objectsStack objects contain other objectsAll objects in stack must have same typeOnly objects may be stored in stacks (no primitive-type values)Syntax: Stack<E>Stack<E> is a generic classE is a class variable representing the base typeReplace E by a specific type to get a stack of that type of elementsClass is in java.util packageDocumentation: http://java.sun.com/j2se/1.5.0/docs/api/java/util/Stack.htmlSee example: StackExample.javaStack<String> stack = new Stack<String>();Creates a stack of strings-extend this to be stack of cats-extend this to be stack of integer
View Full Document