 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 21 – Java Utilities Package and Bit Manipulation Outline 21.1 Introduction 21.2 Vector Class.

Slides:



Advertisements
Similar presentations
11 Copyright © 2005, Oracle. All rights reserved. Using Arrays and Collections.
Advertisements

Stacks, Queues, and Linked Lists
Sequence of characters Generalized form Expresses Pattern of strings in a Generalized notation.
 2003 Prentice Hall, Inc. All rights reserved. Chapter 21 – Java Utilities Package and Bit Manipulation Outline 21.1 Introduction 21.2 Vector Class and.
Java Review Interface, Casting, Generics, Iterator.
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.
Elementary Data Structures CS 110: Data Structures and Algorithms First Semester,
Outline DivideByZeroTes t.java 1 // Fig. 15.1: DivideByZeroTest.java 2 // An exception-handling example that checks for divide-by-zero. 3 import java.awt.*;
 2003 Prentice Hall, Inc. All rights reserved. Chapter 15 – Exception Handling Outline 15.1 Introduction 15.2 Exception-Handling Overview 15.3 Exception-Handling.
 2002 Prentice Hall, Inc. All rights reserved. Chapter 14 – Exception Handling Outline 14.1 Introduction 14.2 When Exception Handling Should Be Used 14.3.
L2. Necessary Java Programming Techniques (Vector) Packages  Java.util import Java.util.*; Classes  Vector Interfaces  Enumeration Java API.
1 L43 Collections (3). 2 OBJECTIVES  To use the collections framework interfaces to program with collections polymorphically.  To use iterators to “walk.
1 CSCD 326 Data Structures I Stacks. 2 Data Type Stack Most basic property: last item in (most recently inserted) is first item out LIFO - last in first.
1 L41 Collections (1). 2 OBJECTIVES  What collections are.  To use class Arrays for array manipulations.  To use the collections framework (prepackaged.
Stacks. 2 Outline and Reading The Stack ADT (§2.1.1) Array-based implementation (§2.1.1) Growable array-based stack (§1.5) Java.util.Stack class Java.util.Vector.
© The McGraw-Hill Companies, 2006 Chapter 17 The Java Collections Framework.
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.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 21 – Java Utilities Package and Bit Manipulation Outline 21.1 Introduction 21.2 Vector Class.
Stacks, Queues, and Deques
Abstract Data Types (ADTs) and data structures: terminology and definitions A type is a collection of values. For example, the boolean type consists of.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 16.1 Test-Driving the Flag Quiz Application.
Data Structures Outline Introduction Self-Referential Classes Dynamic Memory Allocation Linked Lists Stacks Queues Trees.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 22 Java Collections.
Java™ How to Program, 9/e Presented by: Dr. José M. Reyes Álamo © Copyright by Pearson Education, Inc. All Rights Reserved.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 20.1 Test-Driving the Screen Saver Application.
04/29/ Introduction to Vectors?... A vector is a dynamic array. - It can be expanded and shrunk as required - A Component of a vector can be accessed.
Chapter 7 Stacks. © 2004 Pearson Addison-Wesley. All rights reserved 7-2 The Abstract Data Type: Developing an ADT During the Design of a Solution Specifications.
GENERIC COLLECTIONS. Type-Wrapper Classes  Each primitive type has a corresponding type- wrapper class (in package java.lang).  These classes are called.
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.
Copyright © 2002, Systems and Computer Engineering, Carleton University Hashtable.ppt * Object-Oriented Software Development Unit 8.
 2002 Prentice Hall, Inc. All rights reserved. Chapter 20 – Java Utilities Package and Bit Manipulation Outline 20.1 Introduction 20.2 Vector Class and.
Geoff Holmes Palindrome solutions Overview Arrays Collections Enumerators Vector BitSet Stack Dictionary Hashtable Collection Classes (Chapter 19) import.
Generics Collections. Why do we need Generics? Another method of software re-use. When we implement an algorithm, we want to re-use it for different types.
1 Stacks. 2 A stack has the property that the last item placed on the stack will be the first item removed Commonly referred to as last-in, first-out,
Stacks. A stack is a data structure that holds a sequence of elements and stores and retrieves items in a last-in first- out manner (LIFO). This means.
Data structures Abstract data types Java classes for Data structures and ADTs.
 2002 Prentice Hall, Inc. All rights reserved. Chapter 19 – Data Structures Outline 19.1 Introduction 19.2 Self-Referential Classes 19.3 Dynamic Memory.
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures for Java William H. Ford William R. Topp Chapter 8 Collection.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 19.1 Test-Driving the Shipping Hub Application.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 23.1 Test-Driving the Screen Scraping Application.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Tutorial 25 – Ticket Information Application Introducing.
1 The Stack Class Final Review Fall 2005 CS 101 Aaron Bloomfield.
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.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 21.1 Test-Driving the Painter Application.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 8.1 Test-Driving the Car Payment Calculator.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 10.1 Test-Driving the Interest Calculator.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 24.1 Test-Driving the Enhanced Car Payment.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 27.1 Test-Driving the Drawing Shapes Application.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Tutorial 4 – Completing the Inventory Application.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 5.1 Test-Driving the Enhanced Inventory Application.
1 Layout Managers Layout managers –Provided for arranging GUI components –Provide basic layout capabilities –Processes layout details –Programmer can concentrate.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 17.1 Test-Driving the Student Grades Application.
C19: Collection Classes (don’t forget to look at all the online code examples)
 2003 Prentice Hall, Inc. All rights reserved. Chapter 21 – Java Utilities Package and Bit Manipulation Outline 21.1 Introduction 21.2 Vector Class and.
 2003 Prentice Hall, Inc. All rights reserved. Java Utilities Package and Bit Manipulation Outline 21.1 Introduction 21.2 Vector Class and Enumeration.
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures for Java William H. Ford William R. Topp Chapter 20 Ordered.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 28.1 Java Speech API 28.2 Downloading and.
Chapter  Array-like data structures  ArrayList  Queue  Stack  Hashtable  SortedList  Offer programming convenience for specific access.
Click to edit Master text styles Stacks Data Structure.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 7.1 Test-Driving the Dental Payment Application.
Chapter 14 – Exception Handling
Stacks.
CS313D: Advanced Programming Language
L2. Necessary Java Programming Techniques
L2. Necessary Java Programming Techniques
Java Utilities and Bit Manipulation
Fundaments of Game Design
Stacks, Queues, and Deques
Chapter 15 – Exception Handling
Presentation transcript:

 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 21 – Java Utilities Package and Bit Manipulation Outline 21.1 Introduction 21.2 Vector Class and Enumeration Interface 21.3 Stack Class of Package java.util 21.4 Hashtable Class 21.5 Properties Class

 2003 Prentice Hall, Inc. All rights reserved Introduction Utility classes and interfaces –Contained in package java.util Class Vector (array-like objects that grow and shrink dynamically) Interface Enumeration (enables iteration through the elements of a container, like a Vector ) Class Stack (subclass of Vector, standard stack operations like push and pop) Class Hashtable (used to store and retrieve data via “hashing”) Class Properties (support for persistent hash tables)

 2003 Prentice Hall, Inc. All rights reserved Vector Class and Enumeration Interface Class java.util.Vector –Array-like data structures that can resize themselves dynamically –Arrays are fixed in size after memory allocation ( String[] name = new String[25] ) –Vector contains a capacity (number of elements always less than or equal to capacity) –Grows by capacity increment if it requires additional space Vector v = new Vector(); (capacity=10, doubles) Vector v = new Vector(n); (capacity= n, doubles) Vector v = new Vector(n,p); (capacity= n, increment= p )

 2003 Prentice Hall, Inc. All rights reserved Vector Class and Enumeration Interface Class java.util.Vector –Vectors store objects (of any type), but they must be objects and not primitives  This is a job for Wrapper classes –v.add(object) adds new object as the last element in the vector –v.add(i,object) adds new object as element i in the vector (and shifts everything to the right of this one) There must already be an object at element i –v.remove(object) removes object (and shifts everything to the left) –v.remove(i) removes element i (and shifts everything to the left)

 2003 Prentice Hall, Inc. All rights reserved Vector Class and Enumeration Interface Class java.util.Vector –v.capacity() returns capacity –v.size() returns current number of elements –v.trimToSize() sets capacity equal to current number of elements (size) next item added causes capacity to double or increase by p –v.get(i) returns reference to element i –v.set(i,object) changes the object at element i There must already be an object at element i –More Vector methods illustrated in the following example…

 2003 Prentice Hall, Inc. All rights reserved Vector Class and Enumeration Interface Class java.util.Enumeration –Enumeration object generates a series of elements ( Enumeration e = v.elements(); ) v is a Vector elements() method returns an enumeration of all elements in the vector –e.hasMoreElements() –e.nextElement() –Notice the similarity to StringTokenizer –Enumeration can also be used with Hashtable

 2003 Prentice Hall, Inc. All rights reserved. Outline 7 VectorTest.java Line 10 Lines 14, 17 and 19 Line 24 Line 25 1 // Fig. 21.1: VectorTest.java 2 // Using the Vector class. 3 import java.util.*; 4 5 public class VectorTest { 6 private static final String colors[] = { "red", "white", "blue" }; 7 8 public VectorTest() 9 { 10 Vector vector = new Vector(); 11 printVector( vector ); // print vector // add elements to the vector 14 vector.add( "magenta" ); for ( int count = 0; count < colors.length; count++ ) 17 vector.add( colors[ count ] ); vector.add( "cyan" ); 20 printVector( vector ); // print vector // output the first and last elements 23 try { 24 System.out.println( "First element: " + vector.firstElement() ); 25 System.out.println( "Last element: " + vector.lastElement() ); 26 } Create Vector with initial capacity of 10 elements and capacity increment of zero Call Vector method add to add objects to the end of the Vector Call Vector method lastElement to return a reference to the last element in the Vector Call Vector method firstElement to return a reference to the first element in the Vector

 2003 Prentice Hall, Inc. All rights reserved. Outline 8 VectorTest.java Line 34 Line 36 Line 40 Lines // catch exception if vector is empty 29 catch ( NoSuchElementException exception ) { 30 exception.printStackTrace(); 31 } // does vector contain "red"? 34 if ( vector.contains( "red" ) ) 35 System.out.println( "\n\"red\" found at index " + 36 vector.indexOf( "red" ) + "\n" ); 37 else 38 System.out.println( "\n\"red\" not found\n" ); vector.remove( "red" ); // remove the string "red" 41 System.out.println( "\"red\" has been removed" ); 42 printVector( vector ); // print vector // does vector contain "red" after remove operation? 45 if ( vector.contains( "red" ) ) 46 System.out.println( "\"red\" found at index " + 47 vector.indexOf( "red" ) ); 48 else 49 System.out.println( "\"red\" not found" ); // print the size and capacity of vector 52 System.out.println( "\nSize: " + vector.size() + 53 "\nCapacity: " + vector.capacity() ); } // end constructor Vector method contains returns boolean that indicates whether Vector contains a specific Object Vector method indexOf returns index of first location in Vector containing the argument Vector method remove removes the first occurrence of its argument Object from Vector Vector methods size and capacity return number of elements in Vector and Vector capacity, respectively

 2003 Prentice Hall, Inc. All rights reserved. Outline 9 VectorTest.java Line 59 Line private void printVector( Vector vectorToOutput ) 58 { 59 if ( vectorToOutput.isEmpty() ) 60 System.out.print( "vector is empty" ); // vectorToOutput is empty else { // iterate through the elements 63 System.out.print( "vector contains: " ); 64 Enumeration items = vectorToOutput.elements(); while ( items.hasMoreElements() ) 67 System.out.print( items.nextElement() + " " ); 68 } System.out.println( "\n" ); 71 } public static void main( String args[] ) 74 { 75 new VectorTest(); // create object and call its constructor 76 } } // end class VectorTest Vector method elements returns Enumeration for iterating Vector elements Vector method isEmpty returns true if there are no elements in the Vector

 2003 Prentice Hall, Inc. All rights reserved. Outline 10 VectorTest.java vector is empty vector contains: magenta red white blue cyan First element: magenta Last element: cyan "red" found at index 1 "red" has been removed vector contains: magenta white blue cyan "red" not found Size: 4 Capacity: 10

 2003 Prentice Hall, Inc. All rights reserved Stack Class of Package java.util Stack –Implements stack data structure –Extends class Vector –Stores references to Object s (as does Vector ) –Methods Stack() (the only constructor, creates empty stack) push(object) (put object on top of stack) pop() (remove and return object on top of stack) peek() (look at item on top of stack without removing it) empty() (boolean) search(object) (returns distance from top of stack to where item is located or -1)

 2003 Prentice Hall, Inc. All rights reserved. Outline 12 StackTest.java Line 9 Lines 18, 20, 22 and 24 1 // Fig. 21.2: StackTest.java 2 // Program to test java.util.Stack. 3 import java.util.*; 4 5 public class StackTest { 6 7 public StackTest() 8 { 9 Stack stack = new Stack(); // create objects to store in the stack 12 Boolean bool = Boolean.TRUE; 13 Character character = new Character( '$' ); 14 Integer integer = new Integer( ); 15 String string = "hello"; // use push method 18 stack.push( bool ); 19 printStack( stack ); 20 stack.push( character ); 21 printStack( stack ); 22 stack.push( integer ); 23 printStack( stack ); 24 stack.push( string ); 25 printStack( stack ); 26 Create empty Stack Stack method push adds Object to top of Stack

 2003 Prentice Hall, Inc. All rights reserved. Outline 13 StackTest.java Line 32 Line 46 Line // remove items from stack 28 try { 29 Object removedObject = null; while ( true ) { 32 removedObject = stack.pop(); // use pop method 33 System.out.println( removedObject.toString() + " popped" ); 34 printStack( stack ); 35 } 36 } // catch exception if stack is empty when item popped 39 catch ( EmptyStackException emptyStackException ) { 40 emptyStackException.printStackTrace(); 41 } 42 } private void printStack( Stack stack ) 45 { 46 if ( stack.isEmpty() ) 47 System.out.print( "stack is empty" ); // the stack is empty else { 50 System.out.print( "stack contains: " ); 51 Enumeration items = stack.elements(); 52 Stack method pop removes Object from top of Stack Stack method isE mpty returns true if Stack is empty Stack extends Vector, so class Stack may use method elements to obtain Enumeration for Stack

 2003 Prentice Hall, Inc. All rights reserved. Outline 14 StackTest.java 53 // iterate through the elements 54 while ( items.hasMoreElements() ) 55 System.out.print( items.nextElement() + " " ); 56 } System.out.println( "\n" ); // go to the next line 59 } public static void main( String args[] ) 62 { 63 new StackTest(); 64 } } // end class StackTest

 2003 Prentice Hall, Inc. All rights reserved. Outline 15 StackTest.java stack contains: true stack contains: true $ stack contains: true $ stack contains: true $ hello hello popped stack contains: true $ popped stack contains: true $ $ popped stack contains: true true popped stack is empty java.util.EmptyStackException at java.util.Stack.peek(Stack.java:79) at java.util.Stack.pop(Stack.java:61) at StackTest. (StackTest.java:32) at StackTest.main(StackTest.java:63)

 2003 Prentice Hall, Inc. All rights reserved Hashtable Class Hashtable –Data structure that uses hashing Algorithm for determining a key in table –Keys in tables have associated values (data) –Each table cell is a hash “bucket” Linked list of all key-value pairs that hash to that cell Minimizes collisions (handled via hash again, next cell, buckets) –Hashtable() creates empty hashtable with capacity 11 and load factor.75 (table grows larger automatically to meet load factor requirement)

 2003 Prentice Hall, Inc. All rights reserved Hashtable Class Hashtable –containsKey(key) tests if the object is in the hashtable –put(key,object) puts the object in the hashtable using the key –get(key) returns the object in the hashtable using the key

 2003 Prentice Hall, Inc. All rights reserved. Outline 18 WordTypeCount.j ava Line 21 1 // Fig. 21.3: WordTypeCount.java 2 // Count the number of occurrences of each word in a string. 3 import java.awt.*; 4 import java.awt.event.*; 5 import java.util.*; 6 import javax.swing.*; 7 8 public class WordTypeCount extends JFrame { 9 private JTextArea inputField; 10 private JLabel prompt; 11 private JTextArea display; 12 private JButton goButton; private Hashtable table; public WordTypeCount() 17 { 18 super( "Word Type Count" ); 19 inputField = new JTextArea( 3, 20 ); table = new Hashtable(); goButton = new JButton( "Go" ); 24 goButton.addActionListener( 25 Create empty Hashtable

 2003 Prentice Hall, Inc. All rights reserved. Outline 19 WordTypeCount.j ava 26 new ActionListener() { // anonymous inner class public void actionPerformed( ActionEvent event ) 29 { 30 createTable(); 31 display.setText( createOutput() ); 32 } } // end anonymous inner class ); // end call to addActionListener prompt = new JLabel( "Enter a string:" ); 39 display = new JTextArea( 15, 20 ); 40 display.setEditable( false ); JScrollPane displayScrollPane = new JScrollPane( display ); // add components to GUI 45 Container container = getContentPane(); 46 container.setLayout( new FlowLayout() ); 47 container.add( prompt ); 48 container.add( inputField ); 49 container.add( goButton ); 50 container.add( displayScrollPane ); 51

 2003 Prentice Hall, Inc. All rights reserved. Outline 20 WordTypeCount.j ava Line 66 Line 68 Lines 71 and setSize( 400, 400 ); 53 setVisible( true ); } // end constructor // create table from user input 58 private void createTable() { 59 String input = inputField.getText(); 60 StringTokenizer words = new StringTokenizer( input, " \n\t\r" ); while ( words.hasMoreTokens() ) { 63 String word = words.nextToken().toLowerCase(); // get word // if the table contains the word 66 if ( table.containsKey( word ) ) { Integer count = (Integer) table.get( word ); // get value // and increment it 71 table.put( word, new Integer( count.intValue() + 1 ) ); 72 } 73 else // otherwise add the word with a value of 1 74 table.put( word, new Integer( 1 ) ); } // end while 77 Hashtable method get obtains Object associated with key from Hashtable (returns null if neither key nor Object exist) Hashtable method put adds key and value to Hashtable (returns null if key has been inserted previously) Hashtable method containsKey determines whether the key specified as an argument is in the hash table

 2003 Prentice Hall, Inc. All rights reserved. Outline 21 WordTypeCount.j ava Line 83 Line 93 Line } // end method createTable // create string containing table values 81 private String createOutput() { 82 String output = ""; 83 Enumeration keys = table.keys(); // iterate through the keys 86 while ( keys.hasMoreElements() ) { 87 Object currentKey = keys.nextElement(); // output the key-value pairs 90 output += currentKey + "\t" + table.get( currentKey ) + "\n"; 91 } output += "size: " + table.size() + "\n"; 94 output += "isEmpty: " + table.isEmpty() + "\n"; return output; } // end method createOutput 99 Hashtable method keys returns an Enumeration of keys in the hash table Hashtable method size returns the number of key-value pairs in the hash table Hashtable method isEmpty returns boolean that indicates whether Hashtable contains any Object s

 2003 Prentice Hall, Inc. All rights reserved. Outline 22 WordTypeCount.j ava 100 public static void main( String args[] ) 101 { 102 WordTypeCount application = new WordTypeCount(); 103 application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); 104 } } // end class WordTypeCount

 2003 Prentice Hall, Inc. All rights reserved Properties Class Properties –Persistent Hashtable –Properties prop = new Properties(); Can be written to output stream –prop.list(OutputStream); Can be read from input stream –prop.load(InputStream);