Sunteți pe pagina 1din 246

ADVANCED DATA STRUCTURES USING JAVA

4th

edition Spring 2007

Course Syllabus Course Dynamics Class Roadmap Complete Slide Presentation

Instructor:

Jim Adams jima.adams@us.nestle.com jimadams@softwaredynamix.com

Data Structures and Algorithms Using Java

12/29/06

ADVANCED DATA STRUCTURES USING JAVA


4th edition Spring 2007 Course Syllabus Course Dynamics Class Roadmap Complete Slide Presentation

Instructor:

Jim Adams jima.adams@us.nestle.com jimadams@softwaredynamix.com

Data Structures and Algorithms Using Java

12/29/06

Preface to the 4th edition

Special Thanks to Lee Garza for having faith in my teaching ability back in 1996 and to Pat Baker for giving me much advice on teaching and technology.

January 1, 2007

Data Structures and Algorithms Using Java

12/29/06

Contents
Syllabus Complete Presentation Project Requirements Document Supplemental Reading

Data Structures and Algorithms Using Java

12/29/06

Data Structures and Algorithms Using Java

12/29/06

Course Roadmap and Homework Assignments for Data Structures and Algorithms (Java)
Updated on 01/11/2007 for the Spring 2007 Session

Narrative
This document is the project description roadmap for the CSC205 course. It contains project descriptions for all software projects in the CSC205 course. Homework Problems There are 15 Java programs to be written throughout the semester. These programs are a combination of computer science based problems designed to reinforce the course material. Each problem should be turned in separately, stapled together with a cover page. All programs, labs and homework, should have your name, class, problem number and date in comment form in the programs header similar to below.
// // // // // // // // ---------------------------------------------------------Program Name: Prob11.java Problem Number: Project-11 Author: Your Name Course: CSC205 Date: August 19, 2004 Description: This program does the following: some text ----------------------------------------------------------

Series Expansion Project


This Java application project entails prompting the user for a value in degrees and finding the corresponding sine, cosine and tangent of the input value. Use a JOptionPane dialog panel to prompt for the input values. Use a series expansion to determine the sine and cosine of the input values. Compare this value with the Math class values for sine and cosine. Write methods to compute the following: a) Sine b) Cosine c) Tangent. The series expansion for sine of x, is:

The series expansion for the cosine of x, is:

This may look daunting but is very easy once you analyze the problem and break it down into loops and terms. Take each term and find the similarities and sequences. For instance, the exponents are 2, 4, 6, 8, 10, etc for the cosine and 3, 5, 7, 9, etc for the sine. This can easily be controlled in a for loop. You will need a factorial function for the denominator but notice the sequence here, too. The factorial is the same number as the exponent in the numerator. Notice the alternating signs between the terms. Each term should be represented by an iteration of a loop. When you iterate about 20 times, or so, you get an approximation to the sine and cosine.

Project List for Data Structures and Algorithms


Spring 2007 CSC205

HW-1

Course Roadmap and Homework Assignments for Data Structures and Algorithms (Java)
Updated on 01/11/2007 for the Spring 2007 Session

The tangent can be found by using the following algorithm:

So, once you have the sine and cosine methods tested and debugged, then they can be used to derive the tangent.

Array Analysis Project


This project has two parts: A small string generator class and an array utility class. 1) Part-1: This class, named MyString, is a small class with one public method called getRandomString(). It will be used in many of the subsequent classes built in this course so make it generic. The public method returns a random 4-letter string such as DWOK or QWST for example. Feel free to get creative on the constructor. It could set the actual size of the strings to be returned, however, 4 bytes is the requirement. 2) Part-2: The ArrayUtil class is used to generate and populate an array with random integers or random strings. This class will be used in several of the remaining projects so make it neat and clear. When loading the arrays, get the elapsed time. Call the classes from a test harness and load the arrays with 10,000 integers and 10,000 strings. This class should have the following constructors and methods: Constructors
a) ArrayUtil() b) ArrayUtil(int max) Methods c) populateStringArray(); d) populateIntegerArray(); e) getMaximumIntegerIndex() f) getMaximumIntegerValue() g) exists(int) h) exists(string) i) count(int) j) count(string) k) getAverage() l) getSum() m) getArray() n) setValue(int, int) o) setValue(int, String) p) getElapsedTime()
Spring 2007 CSC205

// default 10,000 elements // passed a number of elements to load

: : : : : : : : : : : :

return return return return return return return return return return return return

int int Boolean Boolean int count of the search value int count of the search value double mean value of integers long a reference to the array void void the time in milliseconds

Project List for Data Structures and Algorithms

HW-2

Course Roadmap and Homework Assignments for Data Structures and Algorithms (Java)
Updated on 01/11/2007 for the Spring 2007 Session

q) setStartTime() r) SetEndTime() populateArray(String type);

: Sets the starting time value : Sets the stop time value

Technically, methods c and d, above could be accomplished in a single method. Its your choice. Example, Note that the exists() methods and the setValue() methods are overloaded methods.

Linked List Project


Keep in mind there are three parts to this program. 1) Birth-Order Linked List. Create a linked list of 1,000 random string objects using the MyString class from Part-1 of the above project. Create a basic linked list using Javas linked list class. The 4-letter combos look like ABCS, QDEF, XRYZ, WARH, etc. Once loaded, display the first twenty or so node values. 2) Sorted Linked List. Create a linked list of 1,000 random string objects. This time however, traverse the linked list and insert the string objects in the appropriate location thus keeping the list sorted. The 4-letter combos look like ABCS, QDEF, XRYZ, WARH, etc. Once loaded, display the first twenty or so nodes to prove it is sorted. Display the processing time using the nanoTime() method provided by Java 5.0. 3) Sorted Link List, The Easy Way. Create another linked list of 1,000 random string objects. This time generate the linked list and use the Collections class to sort the list after it has been created. The 4-letter combos look like ABCS, QDEF, XRYZ, WARH, etc. Once loaded, display the first twenty or so nodes to prove it is sorted. Of part-2 and part-3 above, which one is the faster of the two? Display the processing time using the nanoTime() method provided by Java 5.0.

Word Parsing Project


Keep in mind there are two parts to this program. The first part uses Arrays and the second part uses Array Lists. 1.) Surf the net and find an arbitrary page of text of at least 1,000 words, or so -- roughly. Copy and paste the text into a simple text file. Write a Java class to open the text file and read each word from the file. As each word is parsed from the file see if the word exists in the array. If the word does not exist, add it to the array. Keep track of the time it takes to load the array. Keep track of the total words processed and the total words pushed into the array. 2.) The second part of this program is the same as the first part except you need to load an Array List instead of an Array. Print the total count of the words read, total words loaded into the arrays, the time in ms it took to load both collections. Which collection is faster?

3.)

Project List for Data Structures and Algorithms


Spring 2007 CSC205

HW-3

Course Roadmap and Homework Assignments for Data Structures and Algorithms (Java)
Updated on 01/11/2007 for the Spring 2007 Session

Stack Project
1) Emulate a stack by using the Java Linked List class. Push and pop 10,000 random numbers onto the stack. Do a timing analysis. How many can you push onto the stack before you throw a memory exception? Catch the exception. Create a stack class using Javas built-in Stack Class. Push and pop 10,000 random numbers. Do timing analysis. How many can you push onto the stack before you throw a memory exception? Catch the exception. Create a stack class that pushes a random number of objects onto a stack and pops a random number of objects off the stack. Keep track of the exceptions when the stack is empty and when the stack overflows.

2)

3)

Queue Project
Part-1: Here is the algorithm in pseudocode for part-one. Use a Linked List class to emulate the queue. Loop 10,000 times { Generate a random number, n, between 0 and 100. Add n 4-byte string objects to the head of the linked-list. Generate a random number, m, between 0 and 100. Remove m objects from the tail of the lined-list. } Catch all exceptions What is the final size of the linked list? Part-2 Now, go to the web and look up the specification for PriorityBlockingQueue. Repeat Part-1 only this time using the Java-provided PriorityBlockingQueue methods. Which is faster, the linked list or the Java PriorityBlockingQueue class?

Recursion Project
Create a Java class that computes the factorial of a number that is input from the keyboard from a Swing Dialog input box like the one displayed on the right. A factorial is the product of all the numbers up to the number entered. For example, 6-factorial is 720 because 6*5*4*3*2*1 is 720. Six-factorial is written 6! Prompt the user for the numeric input. Keep prompting for values until a zero value is entered. Document your code with plenty of comments. Use recursion. Do the same using the Fibonacci algorithm. You can find this algorithm on the web.

Project List for Data Structures and Algorithms


Spring 2007 CSC205

HW-4

Course Roadmap and Homework Assignments for Data Structures and Algorithms (Java)
Updated on 01/11/2007 for the Spring 2007 Session

Searching Project
Linear and Binary Search Comparison. Randomly populate an array with 10,000 integers. Use the Array Utility Class designed earlier to populate the array. Sort the array in ascending order using the sort algorithm of your choice. Prompt the user for a number to find using a Swing Dialog Box like the one to the right. Search the array using the binary search algorithm and the linear search algorithm. Show the number of iterations or compares it took to find the data using each search algorithm. Also, show a message should there be a no find condition for the number being sought.

Tree Set Project


Part-1 Inherit the random 4-byte string generator class created in a previous project, generate 10,000 random 4-byte strings and add them to a tree set. Capture the time it takes to load the tree set. Print out 20 or 30 entries of the tree set to see that it is sorted. Display the final size of the tree set. Is it 10,000? Why not? Part-2 Using the same data file as input you used on the Word Parser Project, read the file, parse each word and add each of them to a tree set. How many words did you read and how many did you add to the tree set? Is the tree set faster that the Array or Array List used in an earlier project?

Sorting Project
Create three different Java classes to sort data and analyze the five different sort algorithms. 1) Exchange 2) Selection 3) Insertion Write a Bubble Sort (Exchange Sort) class. Randomly populate an array with 10,000 integers. Use the Array Utility Class designed above to populate the array. Sort the array in descending order. Show the number of iterations and swaps and the time in milliseconds it took to sort. This second class will call a Selection Sort class. Randomly populate an array with 10,000 integers. The Array Utility Class designed above to populate the array. Sort the array in descending order. Show the number of iterations and swaps and the time in milliseconds it took to sort this data. Do the same for the Insertion Sort. Add a summary page describing the complete analysis of these sorting algorithms. The goal of this project is to determine which sort method is the quickest.

Hash Set Project


Inherit the random 4-byte string generator created in Project-3, generate 10,000 random 4-byte strings and add them to a hash set. Capture the time it takes to load the hash set. If you change the initial space on the hash algorithm, does it affect the load time? Print out 20 or 30 entries of the hash set. Prompt the user for a 4-byte
Project List for Data Structures and Algorithms
Spring 2007 CSC205

HW-5

Course Roadmap and Homework Assignments for Data Structures and Algorithms (Java)
Updated on 01/11/2007 for the Spring 2007 Session

string and search the hash set for the entered value. Print appropriate error messages if a no- find condition exists.

Vectors Project
Write a Java class that uses the Vector class. Load your vector object with 2,500 random numbers that you convert to individual objects using the Integer wrapper class. Then, loop through and print the first 50 number. Loop, again, and write all 2,500 Integer objects to a disk file using Java File I/O.

File I/O Project


This project illustrates the reading and writing of a disk files data. Download the file named Reels.txt from my web site. It is the page located at http://www.softwaredynamix.com/javashop/sample_data.php. It is a large text file with 1,600 actual magnetic tape volume records. Each record contains a number of fields like reel number, creation date, scratch date, etc. The fields are separated by commas. Download the entire file to your C: Drive. Then use your Java application to process the disk file. Read each line and separate the fields. Store all records into a TreeMap using the first field, reel number, as the tree key. The data records looks like this, TN1921,12/01/2006,12/01/2007,PHX1ND20,DLT,FULL,Imported TN1928,12/01/2006,12/01/2007,PHX1ND28,DLT,FULL,Imported TN1951,12/01/2006,12/01/2007,PHX1ND31,DLT,FULL,Imported Use a JOptionPane dialog panel to prompt for various reel numbers and display all information about the reel if found or a message stating No Find otherwise. Note: There are several ways to tear apart the records some better than others. Research the String class split() method as well as the String Tokenizer class for this parsing exercise. The TreeMap is nice but not particularly handy when processing the entire collection, sequentially. Use the Iterator class and the Set class to create a read method for the TreeMap. Read and display the first 100 records.

Project List for Data Structures and Algorithms


Spring 2007 CSC205

HW-6

Course Roadmap and Homework Assignments for Data Structures and Algorithms (Java)
Updated on 01/11/2007 for the Spring 2007 Session

Swing Project
Using the Java Swing component set, develop your very own file dumper class. This class simply uses the JFileChooser to select a file of your choice. It then opens the file and displays every byte of information in a JTextArea component. Each byte is displayed in hexadecimal. This class should process the input file as binary file so as to obtain each carriage return and line feed to be displayed in your output area. Be sure to include a JMenu for the File Open, Close and Exit functions. Your text-area should look something like this:

Project List for Data Structures and Algorithms


Spring 2007 CSC205

HW-7

Course Roadmap and Homework Assignments for Data Structures and Algorithms (Java)
Updated on 01/11/2007 for the Spring 2007 Session

Statistics Project
This final project deals with arrays and algorithms to calculate some statistics of a data sample. These algorithms show up often in both business and engineering therefore they are very relevant to our learning. The math looks scary but when broken down into components of loops and arrays, the process is easy. Take the mean value of a set of numbers N. The expression below describes the mean in a formal way. Said differently, we sum all the values in the set N and divide by the count. For instance, if we had 75 numbers we sum all 75 numbers and divide by 75 to get the mean, or average, value.

The Project Your project is to provide two separate input paths for the sample data. The first is a manual prompt using a JOptionPane and the other is from a disk file. Each value you harvest is stored in an array element. The Algorithm for Standard Deviation 1. Get the count n of the elements in the array 2. Find the average of all the array elements (xi) 3. Make a second array with the mean minus each original element (xi-x) 4. Square each element of the new array (xi-x)2 5. Get the sum of all the squared elements 6. Divide the sum by n-1 to get the variance 7. take the square root of the variance to get the standard deviation Your Java project should read in a bunch of numbers and subsequently calculate the mean, mode, median and standard deviation. The mode is the most common value. The median is the middle point of the sorted array values.

Project List for Data Structures and Algorithms


Spring 2007 CSC205

HW-8

Data Structures and Algorithms

Chandler Gilbert Community College


CSC205 Data Structures and Algorithms

Subject Overview
Advanced Data Structures (CSC205)

Here is what we will learn


The Phases of Software Development Software Engineering Techniques Specification, Design, Implementation of Java Classes Timing and Algorithm Analysis Collection Classes, Arrays and Arrays Lists Linked Lists Stacks & Queues Advanced Data Structures Tree Sets, Hash Sets Recursive Programming Binary Trees Searching & Sorting Software Reuse with Extended Classes Swing Programming Java File I/O
December 30, 2006 Copyright 2004-2007, Jim Adams SLIDE-2

An Excellent Text

Data Abstraction and Problem Solving with Java, 2nd Ed


by

Frank Carrano and Janet Prichard Publisher: ADDISON-WESLEY,14.10.2005 ISBN: 0321364112

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-3

Tour of the Book


1 Important Features of Java 2 Interfaces and Collection Classes 3 Introduction to Software Engineering 4 Recursion 5 Array Lists 6 Linked Lists 7 Queues and Stacks 8 Binary Trees and Binary Search Trees 9 Balanced Binary Search Trees 10 Tree maps and Tree sets 11 Priority Queues 12 Sorting 13 Searching and The Hash Classes 14 Graphs, Trees, and Networks Appendix 1 Mathematical Background Appendix 3 The Java Collections Framework

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-4

Course Road Map


Sat Jan 13 Classes Begin Mon Jan 15 Observance of M L King Birthday Mon Feb 19 Observance of Presidents' Day Fri Mar 2 Last Day for Withdrawal without Instructor's Signature Mon-Sun Mar 12-18 Spring Break Mon Apr 23 Last Day Student Initiated Withdrawal Accepted Sun May 6 Last Day of Regular Classes Mon-Thu May 7-10 **Final Exams

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-5

Class Structure
Discussions During Each Class
Java, Software Engineering, Computer Science, Abstract Structures

Deliverables
Two Tests Two Exams 15 Java Classes as Homework Projects 11 In-Class Lab Assignments One Critical Thinking Paper

Class and Group Activities


Software Engineering Discussions Students Demonstrating Their Work Student Teach-back

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-6

Homework
See separate Homework Roadmap Document in the tail section of this manual
Class-1 January 22 - Introduction Week In Class: Plan on covering the course syllabus, grading policy, homework projects and some basic software engineering techniques. We will discuss where data structures are used and some Java terminology. We will begin chapter one in the textbook on the object oriented concepts and the phases of software development. Reading: Read Chapter 1 in the text book by Frank Carrano and Janet Prichard. Deliverables: Review and familiarize yourself with this roadmap document. Start researching information for your semester paper, titled, Everything You Ever Wanted to Know About Java Generic Programming Homework: Email Synchronization. Send me an email explaining what you want to learn in this course. Also, state what you feel will be your biggest challenge in this course. Send the email to jimadams@softwaredynamix.com Tests: None.

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-7

Critical Thinking Paper


Critical Thinking Paper Format Six page paper, double-space, typed, with a cover page, contents, introduction, conclusion, analysis, with cited references. Needs to be formal, with page numbers and references. APA or MLA format is fine. Critical Thinking Paper Specific Topic:

Everything You Ever Wanted to Know About Java Generic Programming


It should be a comprehensive paper on Generic Programming
December 30, 2006 Copyright 2004-2007, Jim Adams SLIDE-8

Grading
Grading 100% - 90% A 89% - 80% B 79% - 70% C 69% - 60% D Below 60 Oops

Grading Policy
Assignments are presented with the intent of reinforcing the reading material and topics discussed in the classroom. Late assignments are welcome, but receive a 10 percent reduction for each week they are late. All external class assignments are expected to be typed.

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-9

Grade Distribution
Activity Percent Midterm Exam 20 % Final Exam 24 % 2 Tests 10 % Homework Projects (15 Total) 30 % In Class Labs (11 Total) 11 % Critical Thinking Paper 5% Total Extra Credit Papers 100 % 5%

(2 x 5% each) (15 x 2% each) (11 x 1% each)

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-10

Outcomes and Assessments


Statement Regarding Outcomes and Assessment The faculty and programs at CGCC are dedicated to effective teaching and successful learning with emphasis in the following areas: reading, speaking, listening, writing, mathematics, science, computer application skills, humanities, problem-solving, information literacy, critical thinking, and personal development. Periodically, students will participate in formal and informal assessment activities that will help faculty improve programs and teaching strategies. These activities are designed to facilitate student growth in whatever combination of the above outcomes applies to a course.

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-11

Students With Disabilities


Statement Regarding Students with Disabilities Students with disabilities are required to register for services in the Disability Resources and Services (DRS) office in the Student Center at the beginning of the semester. Do not wait to visit the DRS office if you want support with any CGCC classes. The DRS office will meet with you to determine accommodations based on appropriate documentation. This must be on file before any accommodation will be provided to students. You can contact the DRS office at (480) 857-5188. Faculty are not authorized to provide any accommodations nor can they approve any accommodations for students in this class.

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-12

Plagiarism
Statement Concerning Plagiarism Plagiarism is defined as presenting the work of another as one's own. More than four consecutive words from a source other than the writer constitute plagiarism when the source is not clearly identified in appropriate documentation format. From the CGCC Student Handbook: "Plagiarism includes, but is not limited to, the use of paraphrase or direct quotation, of the published or unpublished work of another person without full and clear acknowledgement. It also includes the unacknowledged use of materials prepared by another person or agency engaged in the selling of term papers or other academic materials."

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-13

Learning Center Services


Information on Learning Center Services The CGCC Learning Center's mission is to support students' academic learning by providing free tutoring and resources to reinforce and supplement classroom instruction and to assist CGCC students to achieve academic success. Free tutoring services are available for many CGCC courses. The Learning Center is located on the second floor of the Library, rooms L227, L228, and L229. The Center also provides instructional support resources in the form of videotapes, software, and print materials. For a schedule of tutoring hours, additional information or assistance contact the Learning Center at (480) 7327231, or visit our website at: http://www.cgc.maricopa.edu/lc

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-14

Student Contact Information


On the 3x5 cards, write:
1. 2. 3. 4. 5.

Name Phone Email Address Where You Work Hobbies or Interests

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-15

Instructor Contact and Background


Instructor Information
Jim Adams (480) 229-5391
Email (Business): jimadams@softwaredynamix.com Email (Home): jim.adams1@cox.net Web Page: www.softwaredynamix.com/javashop/index.php

Division Secretary: Carlene Weberg (480) 732-7043 Software and Systems Engineer since 1978 Teaching at CGCC since 1996 (WIU in 1997, GCC in 1998) Programmed FORTRAN, COBOL, C#, C++, Assembler, VB, Java, Perl, PHP Today all Java and C# BS in Engineering, Mathematics Major MBA Technology Management MS Systems Engineering

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-16

Summary
Text Book Homework & Labs Attendance Class Structure Grading Instructor Contact Information Upon completion of this course, you will have a crisp outlook and deep understanding of some of the critical data structures used in software engineering. Sound Exciting?

Lets go.

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-17

Designing Java Classes

1. 2. 3. 4. 5. 6. 7. 8. 9.

Program Correctness JavaDoc and Java Comments Meaningful Variable Names Constants Code Blocks and White Space Cohesion and Coupling Accessor and Mutator Methods Side Effects Static Methods and Static Fields

Black Box Effect


Black Box Effect Thevenins Theorem in Engineering

Pass in Arguments

Method

Return a Result

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-19

Good Programming Practices


Correctness

A correct program does what it is supposed to do. It conforms to its subdivided specifications, in that its output is correct for ANY acceptable input. Clarity A clear program is easy for people to understand. This is important because 90% of the cost of a large program is writing and maintenance Organize your program into segments
Provide each segment with a heading Subdivide your program

Plan your programs' appearance


Choose a uniform width Align statements of the same weight

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-20

Unique & Meaningful Variable Names


Use Meaningful Names: x = y * z; // not real clear !! distance tax Current new_balance = = = = speed * time; // much more clear cost * tax_rate; Volts * Resistance; new_purchase + old_balance;

int my_result = 0; int count = 0;


Stay away from variable names like:

double char

J23qrsnf abcd;

Variables (identifiers) are case sensitive

int int

Adder; adder;

// these are different variables


Copyright 2004-2007, Jim Adams SLIDE-21

December 30, 2006

Java Constants
Constants are noted as final values in Java
final final final final final double NICKEL_VALUE double PI char LF char CR double E = = = = = 0.05; 3.14159265; 10; 13; 2.71828

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-22

Magic Numbers
Dont use magic numbers Magic numbers are constants that appear in your code
h = 31 * h + ch;

What is the 31? Number of days in December? One less than the ASCII space value of 32? One less than the number of bits in an integer?
final int DAYS_IN_DECEMBER = 31; Much more clear h = DAYS_IN_DECEMBER * h + ch;

final final final final

int SPACE = 32; int LINEFEED = 10; double SQUARE_ROOT_OF_TWO = 1.414213 double PI = 3.1459
Copyright 2004-2007, Jim Adams SLIDE-23

December 30, 2006

Code Blocks & White Space


Java code fragment shown earlier can be written like this: public class Example1 { public static void main( String args[] ) { System.out.println("Welcome to Java Programming!!"); } } Can also be written like this: public class Example1 { public static void main( String args[] ) { System.out.println("Welcome to Java Programming!!"); } }

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-24

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-25

Designing Classes
Classes are named after objects, like nouns
Vehicle class Bank Account class Furniture class Phone class Person class car, truck, etc savings, checking, IRA, mortgage, etc chair, bed, table, lamp, etc cell, analog, digital, home, work man, woman, kid, boy, girl, etc

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-26

Designing Classes
Classes have methods that represent action, like verbs Vehicle class
start_vehicle() stop_vehicle() get_mileage() get_mpg() set_parking_brake() reset_odometer(); get_odometer_reading();

BankAccount class
Deposit(account, amount, date); Withdrawal(account, amount, date); Inquiry(account); Open(account, first name, last name, date); Close(account, date);

Phone class
Initiate_call(number); Answer_call();
December 30, 2006 Copyright 2004-2007, Jim Adams SLIDE-27

Lets Design a Class


The big boss comes in and says we need a class to convert from decimal to binary, hex or octal depending on the users choice. What do we need? Constructors Methods Code Lets Choose a Class Name: NumberConverter
SLIDE-28

December 30, 2006

Copyright 2004-2007, Jim Adams

Lets Design a Class


Lets Work on the Constructor Design. How do we want to invoke this class? Constructors:
NumberConverter(); NumberConverter(int default_base);

NumberConverter nc = new NumberConverter(); NumberConverter nc = new NumberConverter(10);

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-29

Lets Design a Class


Lets deal with the method design Do we want 12 different methods or one large one? Do we want to pass in numbers or strings (hex has both)? Do we want to return string values or numeric?
Methods:
String = get_dec2bin(number); String = get_dec2hex(number); String = get_dec2oct(number); String = get_bin2dec(number); String = get_bin2hex(number); String = get_bin2oct(number); String = get_hex2bin(number); String = get_hex2dec(number); String = get_hex2oct(number); String = get_oct2bin(number); String = get_oct2dec(number); String = get_oct2hex(number);

12 combinations in all Or, do we make a generic method and pass the input and out base.

Or, can we factor some things out..


String = get_dec2bin(number); String = get_dec2hex(number); String = get_dec2oct(number); String = get_bin2dec(number); String = get_hex2dec(number); String = get_oct2dec(number);

String = convertBase(number, base in, base out);


December 30, 2006 Copyright 2004-2007, Jim Adams SLIDE-30

Lets Design a Class


Lets deal with the method design Do we want 12 different methods or one large one? Do we want to pass in numbers or strings (hex has both)? Do we want to return string values or numeric?
String = convert(number_to_convert, base_in, base_out);
public String convert(String num, String baseIn, String baseOut) { . . . }

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-31

Lets Design a Class


What else do we need? Do we need get and set methods?
public int getBase() { } public void setBase(int value) { }

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-32

Recent Real Life Example


I just recently developed an application. Salon and Spa Appointment Manager I started out with the following classes
Stylist Class Vendor Class Client Class Inventory Class Service Class I did not plan well. There is a lot of common information in the Stylist, Client and Vendor classes For example, name, address, city, state, zip, phone, email, etc I could have made a Person Class and inherited much of the common methods and data
SLIDE-33

December 30, 2006

Copyright 2004-2007, Jim Adams

Class Cohesion
Cohesive means a public interface is closely related to the single concept that the class represents For example, this class lacks cohesion:
public class { public public public public public public public public } Purse Purse(){...} void addNickels(int count){...} void addDimes(int count){...} void addQuarters(int count){...} double getTotal(){...} static final double NICKEL_VALUE =0.05; static final double DIME_VALUE =0.1; static final double QUARTER_VALUE =0.25; ...

Why? It has two concepts: purse and coin


SLIDE-34

December 30, 2006

Copyright 2004-2007, Jim Adams

Class Cohesion
Solution: Make two classes:
public class Coin { public Coin(double aValue,String aName){...} public double getValue(){...} } public class Purse { public Purse(){...} public void add(Coin aCoin){...} public double getTotal(){...} }

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-35

Coupling
A class depends on another if it calls one of its methods High Coupling = many class dependencies Minimize coupling to minimize the impact of interface changes

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-36

Dependency Relationships

Purse Class depends on the Coin Class. Coin does NOT depend on Purse

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-37

High and Low Coupling between Classes

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-38

Dependency Relationships
This concept can become tricky and confusing. Do we link (instantiate) another class to get an object or recode the methods in our base class? Do we inherit or do we make an interface? Example: Application that uses XML file access Do we make a separate XML class that reads and writes and otherwise processes XML files, or Do we include the XML routines in the base class. Effect If we inherit the standalone XML class then we need to include that class whenever we distribute the base class. If we include, or incorporate, the XML class methods into the base application, then we can distribute one class.
December 30, 2006 Copyright 2004-2007, Jim Adams SLIDE-39

Accessor and Mutator Methods


Accessor: does not change the state of the implicit parameter Mutator: changes the state of the implicit parameter Rule of thumb: Mutator should return void Immutable Class: all methods of the class are accessor methods
private int getBalance(String account) { this.balance = 0.0; } // implicit parameter // explicit parameter

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-40

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-41

Side Effects
Side Effect: any observable change outside the implicit parameter like doing something other than what the method was designed to do. Example: Getter method that updates
public double balanceInquiry(BankAccount acct) { this.inquiry_date = Date(today); // questionable sendUserEmail(client_name, acct); // definite side effect this.inquiries++; // definite side effect return(this.balance); // okay }

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-42

Side Effects
public void deposit(double amount, BankAccount acct) { this.balance = this.balance + amount; } // No Side Effect

public void deposit(double amount, BankAccount acct) { this.balance = this.balance - amount; printBalance(acct); // Side Effect } // In the main, call the methods separately deposit(1234.90, "YourAccount"); printBalance("YourAccount");

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-43

Static Methods
Every method must be in a class All methods wrote up to now are Instance Methods Static Methods are sometimes called Class Methods Math.sqrt(x) Math is a Class and acts like an object
Public static boolean approxEqual(double x, double y) { final double EPSILON = 1E-14; if (x==0) return Math.abs(y); if (y==0) return Math.abs(x); return Math.abs(x-y); } Notice no local variables. We do not need a copy of this function each time we call it. Static methods can only be invoked by a class name, not an object name
December 30, 2006 Copyright 2004-2007, Jim Adams SLIDE-44

Static Fields
One field per class
public class BankAccount Static { private double balance; private int accountNumber; Stack private static int lastAssignedNumber; } Heap public BankAccount() { lastAssignedNumber++; // increment static field accountNumber = lastAssignedNumber; // set instance field }

Minimize the use of static fields. Static final fields are ok

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-45

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-46

Scope
Scope of variable: region of program where you can refer to the variable by its name Local variable scope: from definition to end of block Class scope: all methods of the class Must qualify public members outside scope, e.g. Math.sqrt
public class BankAccount { private double balance; // class scope private int accountNumber; private static int lastAssignedNumber; public BankAccount() { long newAccountNumber=0; // local scope lastAssignedNumber++; accountNumber = lastAssignedNumber;

} } // end of class

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-47

Scope
Overlapping scope: local scope wins over class scope
public class Coin { public void draw(Graphics2D g2) { String name = "SansSerif"; // local scope g2.setFont(new Font(name, . . .)); // local name g2.drawString(this.name, . . .); // field name } private String name; . . . } // class scope

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-48

Scope In the constructor


public class Encrypter { private int counter=0; // class variable

public Encrypter(int counter) { this.counter = counter; } }

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-49

Scope
Instantiating an Object from a Class
public static void main(String[] args) { Encrypter enc = new Encrypter(90); enc.somePublicMethod(); } public class Encrypter { private int counter=0;

// class variable

public Encrypter(int counter) { this.counter = counter; }

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-50

Coupling Example
public class Driver { public Driver() { }
Using Our Project as an example

public static void main(String[] args) { Harvest h = new Harvest(); // Get a Public Variable System.out.println(h.count); System.out.println(Harvest.cnt); // Get a static Variable System.out.println(h.getCounter()); // Get a private Var } }

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-51

Coupling Example
public class Harvest { private int counter=80; public int count=90; public static int cnt=100; public Harvest() { } public int getCounter() { return(counter); } }
// private instance Variable // public instance Variable // public static Variable

Using Our Project as an example

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-52

Summary
Program Correctness Javadoc Class Design Java Constants Variable Scope Static Methods Coupling Accessor and Mutator methods Further Research Javadoc Designing Classes Static Variables and Methods Use Cases UML Diagrams Extreme Programming SDLC Waterfall Methodology Spiral Model Concurrent Development Model Agile Development Navigation Analysis Systems Theory

References http://www.agilemodeling.com/essays/agileSoftware Development.htm

Software Engineering, Sixth Edition by Roger Pressman Software Engineering Volume 1: The Development Process. IEEE Press.

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-53

Java Inheritance
Goals To understand inheritance To understand software reusability

Inheritance
Often you will be in a situation where a class is close to what you need. Perhaps the class you need requires some minor alteration
Adding a few methods Changing a few methods

Java, and Object Oriented Languages in general, provide support for this type of situation. The original class is called the Super Class (or
Parent Class or Base Class)

The new class is called the Extended Class (or


derived class or child class or sub class)

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-55

Extending a Class
Extending a class
Defining a new class (to create a new type) can involve a lot of effort. Sometimes you have an option that can greatly reduce the effort required to create your new type. If a class (type) already exists that is close to what you need, you can often extend that class to produce a new class that is closer to what you need. In many cases, this will require much less effort than that required to start from scratch and define a new class to establish a new type. The ability to extend one class into another new class is the essence of inheritance. According to the current jargon, the new class is called the subclass and the class that was extended is called the superclass.
December 30, 2006 Copyright 2004-2007, Jim Adams SLIDE-56

Extending a Class
What is inherited?
The subclass inherits all of the variables and all of the methods defined in the superclass It's like you had completely defined the new class from scratch and reproduced all of the code already defined in the existing superclass.

Code reuse
Inheritance makes it possible to define a new class with a minimum requirement to write new code by reusing the code that was previously written into the superclass. Sometimes you can get by with simply extending the existing class. Sometimes it is necessary to make changes to the existing class to improve its ability to be extended in a meaningful way. It all depends on how the existing class was designed in the first place.
SLIDE-57

December 30, 2006

Copyright 2004-2007, Jim Adams

Inheritance
Let's Look At A Bank Account We can have many types of accounts.
Savings Personal Checking Business Checking Student Loans Home Loans Certificate of Deposit

They are different but have some similarities.


Each as a balance Each has an account holder Some have deposits and withdrawals, some have payments

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-58

Inheritance
Let's Look At A Vehicle We can have many types of vehicles.
Cars Trucks Pick-up Trucks SUV's Golf Carts

They are different but have some similarities.


Each as an engine Each has wheels Each has a start mechanism Each can turn left and right Some have tail gates and others have trunks Some have 4 wheels, some have 18

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-59

Inheritance
Bank Account Class Vehicle Class

Bank Account Super Class

Vehicle Super Class

Savings Account Sub Class

Checking Account Sub Class

Car Sub Class

Truck Sub Class

Savings Account and Checking Account Class Would Extend the Bank Account Class

Car and Truck Class Would Extend the Vehicle Class

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-60

public class Vehicle { public Vehicle() { }

Vehicle Class (First Look)

public void setEngineSize(int ci) { System.out.println("Setting Engine Size to " + ci + " Cubic Inches"); } public void setTransmissionSpeeds(int gears) { System.out.println("Setting Transmission to " + gears + "-Speed"); } public void startEngine(String msg) { System.out.println("Starting the " + msg); } public void moveForward(String msg) { System.out.println("Moving the " + msg + " forward"); } public void turnLeft(String msg) { System.out.println("Turning the " + msg + " to the left"); }
December 30, 2006 Copyright 2004-2007, Jim Adams SLIDE-61

Car Class (First Look)


public class Car extends Vehicle { public Car() { setEngineSize(283); // derived from Vehicle Class setTransmissionSpeeds(3); startEngine("Car"); moveForward("Car"); turnLeft("Car"); } }

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-62

public class Truck extends Vehicle { public Truck() { setEngineSize(427); // derived from Vehicle Class setTransmissionSpeeds(4); startEngine("Truck"); moveForward("Truck"); turnLeft("Truck"); lowerTailGate(); } private void lowerTailGate() // specific to truck class { System.out.println("Lowering Tail Gate"); } }

Truck Class (First Look)

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-63

Inheritance
Let's look at some more techniques used by Java super this

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-64

public class Vehicle {

Vehicle Class (Second Look)


String vehicleModel; public Vehicle() { } public void setEngineSize(int ci) { System.out.println("Setting Engine Size to " + ci + " Cubic Inches"); } public void setTransmissionSpeeds(int gears) { System.out.println("Setting Transmission to " + gears + "-Speed"); } public void startEngine(String msg) { System.out.println("Starting the " + msg); } public void moveForward(String msg) { System.out.println("Moving the " + msg + " forward"); } public void turnLeft(String msg) { System.out.println("Turning the " + msg + " to the left"); } public void getVehicleModel() { System.out.println("Vehicle Model is " + this.vehicleModel); }
December 30, 2006 Copyright 2004-2007, Jim Adams SLIDE-65

public class Truck extends Vehicle { String truckModel;

Truck Class (Second Look)


public Truck(String model) { super.vehicleModel = model; this.truckModel = model; setEngineSize(427); setTransmissionSpeeds(4); startEngine("Truck"); moveForward("Truck"); turnLeft("Truck"); lowerTailGate(); getVehicleModel(); } private void lowerTailGate() { System.out.println("Lowering Tail Gate"); }

// sets model in super class // sets model in this class

}
December 30, 2006 Copyright 2004-2007, Jim Adams SLIDE-66

public class Car extends Vehicle { String carModel; public Car(String model) { super.vehicleModel = model; // sets model in super class this.carModel = model; // sets model in this class setEngineSize(283); setTransmissionSpeeds(3); startEngine("Car"); moveForward("Car"); turnLeft("Car"); getVehicleModel(); } }

Car Class (Second Look)

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-67

Examples
Can you think of any examples of inheritance?
Construction Worker Two-Story Home Tiger Elephant Cuckoo Clock Dime Car JPanel

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-68

Examples
Can you think of any examples of inheritance?
Construction Worker Employee Person Two-Story Home Dwelling Tiger Carnivore Animal Organism Elephant Herbivore Animal Organism Cuckoo Clock Clock Dime Coin Money Car Vehicle JPanel JComponent

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-69

Examples
Swing Components
JComponent

JPanel

JTextComponent

JLabel

JAbstractButton

JTextArea

JTextField

JToggleButton

JButton

JCheckBox

JRadioButton

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-70

Event Handling MouseAdapter Example


/** * Mouse Listener Class for Table row Highlight * Table Row was selected. Process it. * Written 02/12/2005 */ public class MyMouseAdapter extends MouseMotionAdapter { public void mouseMoved(MouseEvent e) { int itsRow = 0; int itsColumn = 0; JTable aTable } } = (JTable)e.getSource();

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-71

An Interface
Objects define their interaction with the outside world through the methods that they expose. Methods form the object's interface with the outside world; the buttons on the front of your television set, for example, are the interface between you and the electrical wiring on the other side of its plastic casing. You press the "power" button to turn the television on and off. In its most common form, an interface is a group of related methods with empty bodies. A bicycle's behavior, if specified as an interface, might appear as follows:

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-72

An Interface
Creating your own interface. Notice the empty methods interface Bicycle { void changeCadence(int newValue); void changeGear(int newValue); void speedUp(int increment); void applyBrakes(int decrement); }

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-73

An Interface
Is a model or template of an object. It has predefined methods in name only. You must supply the code. /* * Action Listener Interface */ private class PopUpMenuListener implements ActionListener { public void actionPerformed(ActionEvent e) { JMenuItem item = (JMenuItem) e.getSource(); String name = item.getName(); if (name.equals("Item13")) { addBreak(); } } }
December 30, 2006 Copyright 2004-2007, Jim Adams SLIDE-74

// Break

An Interface
Is a model or template of an object
/** * Mouse Motion Listener. * Changes the mouse cursor * Sets global variables */ private class MouseHoverRight implements MouseMotionListener { public void mouseMoved(MouseEvent evt) { rightArrow.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); rightArrow.setToolTipText("Move Forward One Day"); } public void mouseDragged(MouseEvent evt) { } }

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-75

Why is Reuse Important?


1. 2. 3. 4.

Labor Cost Time Constraints Complexity Improved Quality

Code reuse pays off for ING - The company saved about $300,000 and 1,200 manhours ComputerWorld. News Story by Lucas Mearian. JANUARY 10, 2005. Code reuse: Does anyone still do this? (Jeff Key Web Site) It startles me whenever I see add-ins, IDEs or people touting code libraries and code reuse. Is anyone still copying and pasting code? I have a couple standard comment headers and whatnot that I store in the VS.NET toolbar for reuse, but no code. With all of the template-based code generators available now, I can't imagine why anyone would do this. On a related note, I get the heebie-jeebies when people mention pulling code from old apps to reuse in a new app, even if it was their own code. The great thing about being in this profession is that you learn every day. Any time anyone mentions pulling old code, I suggest pulling the ideas and leave the code where it is. The hard part isn't writing the code, it's the concept behind it. Take what you've learned and write something new and wonderful. Conceptual reuse, that's where it's at.
Copyright 2004-2007, Jim Adams SLIDE-76

December 30, 2006

Why is Reuse Important?


Quantifiable benefits of reuse, in terms of cost savings, improved quality, and improved long-term productivity, have long been a goal rather than a reality for IT shops. (December 3, 2004. by Liz Barnett, with Carl Zetie, Carey Schwaber Forrester Research)

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-77

Design Patterns

Design Patterns
Design patterns are recurring solutions to software design problems you find again and again in real-world application development. Patterns are about design and interaction of objects, as well as providing a communication platform concerning elegant, reusable solutions to commonly encountered programming challenges.

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-78

Summary
Summary Extending an existing class often provides an easy way to create a new type. This is primarily true when an existing class creates a type whose features are close to, but not identical to the features needed in the new type. When an existing class is extended to define a new class, the existing class is often called the superclass and the new class is often called the subclass. The subclass inherits all of the variables and all of the methods defined in the superclass and its superclasses. Inheritance provides a formal mechanism for code reuse.

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-79

Software Engineering
1. 2. 3. 4. 5. 6. 7.

Software Engineering Processes Software Development Phases Specification and Design Methodologies Software Analysis Software Failure Issues Faced Today UML, Preconditions, Post Conditions

What is Engineering?
The use of scientific (including mathematical) principles to construct artifacts "Application of knowledge of the mathematical and natural sciences, gained by study, experience and practice, to the efficient use of the materials and forces of nature". (MS Encarta) "Creation and design of practical solutions to real physical problems"

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-81

What is Software Engineering?


"The systematic approach to the development, operation, maintenance and retirements of software"- IEEE Standard
Glossary of Software Engineering Terminology, 1983

The construction of quality software with a limited budget and a given deadline in the context of constant change. The establishment and use of sound engineering principles in order to obtain, economically, software that is reliable and works efficiently on real machines.
(Bauer 1969)

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-82

What's So Special About Software?


Major cost/effort is in design, not manufacture Functionality offered by software is unbounded Complex system decomposition and interacting processes Discontinuous behavior Changes to specification and design have side effects No agreed means of assuring quality Requirements often ill-defined and subject to change

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-83

Software Failures
Patriot missile 1991 The Patriot system at Dhahran failed to track and intercept the Scud missile because of a software problem in the system's weapons control computer. This problem led to an inaccurate tracking calculation that became worse the longer the system operated. At the time of the incident, the system had been operating continuously for over 100 hours. By then, the inaccuracy was serious enough to cause the system to look in the wrong place for the incoming Scud missile Ariane 5 rocket 1996 On June 4, 1996 an unmanned Ariane 5 rocket launched by the European Space Agency exploded just forty seconds after its lift-off from Kourou, French Guiana. The rocket was on its first voyage, after a decade of development costing $7 billion. The destroyed rocket and its cargo were valued at $500 million. The cause of the failure was a software error in the inertial reference system. Specifically a 64 bit floating point number relating to the horizontal velocity of the rocket with respect to the platform was converted to a 16 bit signed integer. The number was larger than 32,767, the largest integer store-able in a 16 bit signed integer Taurus (London stock exchange system) 1993 Another failure was the collapse of the Taurus trading system of the London Stock Exchange. Taurus would have replaced the shuffling of six sorts of paper among three places over two weeks with a computerized system able to settle trades in three days. The five-year Taurus development effort, which sources estimated cost hundreds of millions of dollars, was termed a disaster, and the project was abandoned in March 1993.
December 30, 2006 Copyright 2004-2007, Jim Adams SLIDE-84

Software Failures
Denver airport baggage handling system Despite the fact that a company well known for being "among the best" who worked on the DIA Baggage Handling System, BAE Automated Systems, there were so many problems that it caused the DIA opening to be postponed 4 times. Mostly managerial and social factors caused most of the major problems with this baggage system. They made it much more complex, having BAE to design the baggage system around the architecture of the airport. There was an obvious lack of communication and proper planning with the designers and the managers. London ambulance system (1993) In Britain, 1993, an incident occurred which forced the London Ambulance Service to abandon its emergency system after it performed disastrously on delivery, causing delays in answering calls. An independent inquiry ordered by British government agencies found that the ambulance service had accepted a suspiciously low bid from a small and inexperienced supplier. The inquiry report, released in February 1993, determined that the system was far too small to cope with the data load. For an emergency service, the system error would not only cause the loss of money, but more essentially, fail to dispatch ambulances correctly and promptly upon the arising of critical situations. Therac-25 Radiation Machine Between June 1985 and January 1987, six known accidents involved massive overdoses by the Therac-25 -- with resultant deaths and serious injuries. They have been described as the worst series of radiation accidents in the 35-year history of medical accelerators.
December 30, 2006 Copyright 2004-2007, Jim Adams SLIDE-85

Software Engineering Code of Ethics


Software engineers shall commit themselves to making the analysis, specification, design, development, testing and maintenance of software a beneficial and respected profession. In accordance with their commitment to the health, safety and welfare of the public, software engineers shall adhere to the following Eight Principles: 1. PUBLIC Software engineers shall act consistently with the public interest. 2. CLIENT AND EMPLOYER Software engineers shall act in a manner that is in the best interests of their client and employer consistent with the public interest. 3. PRODUCT Software engineers shall ensure that their products and related modifications meet the highest professional standards possible. 4. JUDGMENT Software engineers shall maintain integrity and independence in their professional judgment. 5. MANAGEMENT Software engineering managers and leaders shall subscribe to and promote an ethical approach to the management of software development and maintenance. 6. PROFESSION Software engineers shall advance the integrity and reputation of the profession consistent with the public interest. 7. COLLEAGUES Software engineers shall be fair to and supportive of their colleagues. 8. SELF Software engineers shall participate in lifelong learning regarding the practice of their profession http://onlineethics.org/codes/softeng.html and shall promote an ethical approach to the practice of the profession.
December 30, 2006 Copyright 2004-2007, Jim Adams SLIDE-86

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-87

Six Key Programming Issues


Modularity Modifiability Ease of Use Fail-safe Programming Style Debugging

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-88

Six Key Programming Issues


Modularity Why is this important?
Constructing the program Debugging the program Reading the program Modifying the program Eliminating redundant code

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-89

Six Key Programming Issues


Modifiability
Methods Named constants

Ease of Use
Prompt the user for input values Echo the input

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-90

Six Key Programming Issues


Fail-safe programming
Guard against errors in the input data Guard against errors in program logic
Method should enforce their preconditions

Style
Extensive use of methods Use private data fields Error handling Readability Documentation

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-91

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-92

Software Development Methodologies


Design Methodologies Encompasses all activities from initial analysis until obsolescence
Basic Design Methodology Analysis and Design Methodology Waterfall Methodology Spiral Methodology SDLC Extreme Programming Methodology (XP) Agile Development Methodology PBR Plan, Build, Run
SLIDE-93

December 30, 2006

Copyright 2004-2007, Jim Adams

Basic Design Methodology


1. 2. 3. 4. 5. 6. 7. 8.

Define objectives Preliminary design of classes Write the code Compile the code Run the program Test and debug Maintain and modify Document

Today, we tend to use an iterative approach

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-94

Basic Design Methodology


Specification of the task Design the solution Implementation of the solution Analysis of the solution Testing and Debugging Maintenance and evolution of the system Obsolescence

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-95

Waterfall Methodology (1 of 2)
Analysis Decide what the project is suppose to do Output: requirements document Design Plan how to implement the system Output:
description of classes and methods diagrams showing the relationships among the classes
December 30, 2006 Copyright 2004-2007, Jim Adams SLIDE-96

Waterfall Methodology (2 of 2)
Implementation Write and compile the code Output: completed code Testing Run tests to verify the program works correctly Output: a report of the tests and their results Deployment Install the program and begin using it

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-97

Analysis and Design Methodology


A. Conceptual Design Phase -- During the conceptual design phase, agency management identifies the need for a system, and develops a high level project plan. B. Planning Phase -- During the planning phase, system developers and users determine functional, quality, and architecture requirements of the system identified in the conceptual design phase, design the system to meet those requirements, and plan for development and implementation. C. Development Phase -- During the development phase, system developers code and test the system designed in the planning phase, and prepare for training and implementation. D. Implementation Phase -- During the implementation phase, users learn and test the system to ensure it meets their requirements. If the users accept the system, systems developers install and convert to the new system. E. Post Implementation/System Support Phase -- During the post implementation/system support phase, management, users, and systems developers continuously monitor the implemented system to ensure it measures up to the expectations and requirements developed in previous phases, and to enhance the system as needed to increase the system's useful life.
December 30, 2006 Copyright 2004-2007, Jim Adams SLIDE-98

Systems Development Life Cycle


Preliminary Investigation Maintenance

Systems Analysis

Implementation

Systems Design Systems Development

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-99

The Spiral Model

Start Here

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-100

Extreme Programming (XP) (1 of 2)


Development methodology that strives for simplicity by removing formal structure and focusing on best practices Realistic planning Customers make business decisions Programmers make technical decisions Small releases Release a useful system quickly Release updates on a short cycle Simplicity Design as simply as possible instead of preparing for future complexities Testing Programmers and customers write test cases Test continuously Refactoring Restructure the system continuously to improve code and eliminate duplication

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-101

Extreme Programming (XP) (2 of 2)


Pair programming Two programmers write code on the same computer Collective ownership All programmers change all code as needed Problematic in the real world. Continuous integration Build the entire system and test it whenever a task is complete 40-hour week Don't cover up unrealistic schedules with heroic effort On-site customer A customer is accessible to the programming team at all times Coding standards Follow standards that emphasize self-documenting code
December 30, 2006 Copyright 2004-2007, Jim Adams SLIDE-102

Agile Development Methodology

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-103

Many Methodologies
1. Basic Design Methodology 2. Analysis and Design Methodology 3. Waterfall Methodology 4. Spiral Methodology 5. SDLC 6. Extreme Programming Methodology (XP) 7. Agile Development Methodology 8. PBR Plan, Build, Run 9. SCRUM 10. Adaptive Software Methodology 11. Crystal
Software Engineering. Theory and Practice. (2006). Pfleeger and Atlee.
December 30, 2006 Copyright 2004-2007, Jim Adams SLIDE-104

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-105

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-106

Unified Modeling Language


Class Diagram models class structure and contents using design elements such as classes, packages and objects. It also displays relationships such as containment, inheritance, associations and others Interaction Diagrams
Sequence Diagram displays the time sequence of the objects participating in the interaction. This consists of the vertical dimension (time) and horizontal dimension (different objects) Collaboration Diagram displays an interaction organized around the objects and their links to one another. Numbers are used to show the sequence of messages.1

State Diagram displays the sequences of states that an object of an interaction goes through during its life in response to received stimuli, together with its responses and actions Activity Diagram displays a special state diagram where most of the states are action states and most of the transitions are triggered by completion of the actions in the source states. This diagram focuses on flows driven by internal processing Physical Diagrams
Component Diagram displays the high level packaged structure of the code itself. Dependencies among components are shown, including source code components, binary code components, and executable components. Some components exist at compile time, at link time, at run times well as at more than one time Deployment Diagram displays the configuration of run-time processing elements and the software components, processes, and objects that live on them. Software component instances represent run-time manifestations of code units.
December 30, 2006 Copyright 2004-2007, Jim Adams SLIDE-107

Unified Modeling Language


A Use Case is a set of scenarios that describe an interaction between a user and a system. A use case diagram displays the relationship among actors and use cases. The two main components of a use case diagram are use cases and actors

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-108

Unified Modeling Language


Class diagrams are widely used to
describe the types of objects in a system and their relationships. Class diagrams model class structure and contents using design elements such as classes, packages and objects Class diagrams also display relationships such as containment, inheritance, associations and others

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-109

Unified Modeling Language


Another common relationship in class diagrams is a Generalization. A generalization is used when two classes are similar, but have some differences

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-110

Unified Modeling Language


Interaction diagrams model the behavior of
use cases by describing the way groups of objects interact to complete the task. The two kinds of interaction diagrams are sequence and collaboration diagrams

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-111

Unified Modeling Language


Collaboration diagrams are also relatively easy to draw. They show the relationship between objects and the order of messages passed between them. The objects are listed as icons and arrows indicate the messages being passed between them.

UML Excerpts from http://pigseye.kennesaw.edu/~dbraun/csis4650/A&D/UML_tutorial/activity.htm

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-112

Unified Modeling Language


State diagrams are used to describe the behavior of a system. State diagrams describe all of the possible states of an object as events occur. Each diagram usually represents objects of a single class and track the different states of its objects through the system

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-113

Unified Modeling Language


Activity diagrams describe the workflow
behavior of a system. Activity diagrams are similar to state diagrams because activities are the state of doing something. The diagrams describe the state of activities by showing the sequence of activities performed. Activity diagrams can show activities that are conditional or parallel

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-114

Unified Modeling Language


There are two types of Physical diagrams: deployment diagrams and component diagrams. Deployment diagrams show the physical relationship between hardware and software in a system. Component diagrams show the software components of a system and how they are related to each other. These relationships are called dependencies

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-115

The Interaction ModelSequence Diagram


Composed of four elements:
use-cases sequence diagrams state diagrams a user interface prototype

Use Case Diagram

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-116

Unified Modeling Language


Books Martin Fowler, Kendall Scott: UML Distilled, Addison-Wesley 2000 Grady Booch, et al: The Unified Modeling Language User Guide, Addison-Wesley James Rumbaugh, et al: The Unified Modeling Language Reference Manual, AddisonWesley Ivar Jacobson, et al: Unified Software Development Process, Addison-Wesley Jos B. Warmer, Anneke G. Kleppe: The Object Constraint Language : Precise Modeling With UML, Addison-Wesley Online UML Resources Rational Software The Object Management Group The UML Center The UML Zone GDpro UML Modeling Tools Rational Rose GDpro 5.0

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-117

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-118

Preconditions and Post-conditions


An important topic: preconditions and postconditions. They are a way of specifying what a method or function accomplishes. Frequently, a programmer must communicate precisely what a function accomplishes, without any indication of how the function does its work. Can you think of a situation where this would occur ?
December 30, 2006 Copyright 2004-2007, Jim Adams SLIDE-119

Example
You are the head of a programming team and you want one of your software developers to write a method for part of a project.
HERE ARE THE REQUIREMENTS FOR A METHOD THAT I WANT YOU TO WRITE.

I DON'T CARE WHAT ALGORITHM THE METHOD USES, AS LONG AS THESE REQUIREMENTS ARE MET.

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-120

What are Pre-conditions and Post-conditions?

One way to specify such requirements is with a pair of statements about the function. The pre-condition statement indicates what must be true before the function is called. The post-condition statement indicates what will be true when the function finishes its work.
December 30, 2006 Copyright 2004-2007, Jim Adams SLIDE-121

Example
void { // // // } writeSqrt( double x) Precondition: x >= 0. Postcondition: The square root of x has been written to the standard output.

The precondition and post-condition appear as comments in your program.

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-122

Example
Which of these method calls meet the precondition ?
writeSqrt(-10); writeSqrt(0); writeSqrt(5.6);

void { // // // }

writeSqrt( double x) Precondition: x >= 0. Postcondition: The square root of x has been written to the standard output.

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-123

Example
void { // // // } writeSqrt( double x) Precondition: x >= 0. Postcondition: The square root of x has been written to the standard output.

The post condition always indicates what work the function has accomplished. In this case, when the function returns the square root of x.

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-124

Another Example
bool { // // // // // // } is_vowel( char letter ) Precondition: letter is an uppercase or lowercase letter (in the range 'A' ... 'Z' or 'a' ... 'z') . Postcondition: The value returned by the function is true if Letter is a vowel; otherwise the value returned by the function is false.

true

What values will be returned by these method calls ? is_vowel( 'A' ); is_vowel(' Z' ); is_vowel( '?' );

false Nobody knows, because the precondition has been violated.


Copyright 2004-2007, Jim Adams SLIDE-125

December 30, 2006

Careful programmers follow these rules: When you write a method or function, you should make every effort to detect when a precondition has been violated. If you detect that a precondition has been violated, then print or display an error message and halt the program.

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-126

Summary
Summary
1. 2. 3. 4. 5. 6.

Engineering Methodologies Software Engineering Processes Software Development Phases Specification and Design Methodologies Implementation of Software Applications Software Failure Code of Ethics

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-127

Algorithms
1. 2. 3. 4. 5.

Software Algorithms Time Analysis Software Testing Big O Notation Debugging Techniques

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-129

Algorithms
Series Expansion Algorithms
Taylor Series

1. 2. 3. 4.

Analyze the algorithm Look for similarities in each term Numerator has x1, x3, x5, x7, xn The denominator is the same as the numerator exponent as a factorial Each term can be solved inside a loop Could make a method for the denominator and one for the numerator
December 30, 2006 Copyright 2004-2007, Jim Adams SLIDE-130

5. 6.

Algorithms
Series Expansion Algorithms

Where would you start on the cosine expansion above? Taylor Series Expansion for Cosine

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-131

Algorithms
Series Expansion Algorithms Output 20.085536921517665 Where would you start on the expansion above?
public double e(double x) { double result double numerator double denominator for (int n=0; n<20; { numerator = denominator = result = } return(result); } n++) Math.pow(x,n); factorial(n); result + (numerator / denominator); =0.0; =0.0; =0.0;

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-132

Algorithms
Hundreds of Series Expansion Algorithms Binomial Statistical Exponential Trigonometric Differentials Integrals Fourier Transformations Encryption

pi=4*(1 - 1/3 + 1/5 - 1/7 + 1/9 - 1/11 + 1/13 + ...)

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-133

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-134

Time Analysis
Methods 1. Count the number of loop iterations, swaps, etc 2. Count the times each array element is accessed 3. Devise a software stopwatch and count the milliseconds of time during execution 4. Sum up all the actions Each access takes some amount of CPU cycles Some more, some less, but they all take cycles Assume an if test takes 20 cycles per use, for example Assume an assignment statement takes 8 CPU cycles 5. Count the number of Operators Uses Big O Notation

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-135

Time Analysis
Time for f(n) instructions to execute on a machine that executes 1 billion instructions per second. (1 Gigahertz)

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-136

Time Analysis
Consider the following example:
1. System.out.println(Enter a number); 2. count=0; 3. sum=0; 4. num=Integer.parseInt(keyboard.readLine()); 5. while (num != -1) 6. { 7. sum = sum + num; 8. count++; 9. num = Integer.parseInt(keyboard.readLine()); 10. } 11. if (count != 0) 12. average = sum/count; 13. else 14. average=0;

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-137

Time Analysis
The program has 4 operations before the while loop (Lines 2-5) It has 3 or 4 operations after the while loop, depending on the value of count (Lines 11-14) The while loop has one operator on line 5 with 4 operations inside the loop (Lines 7-9) So, if the loop executes 10 times then there are 51 operations (5 operations times 10 plus the while statement itself) plus 4 before the loop and plus 4 or 5 depending on count after the loop. Generalizing, it is (5n + 9) or (5n + 10) With very large values of n, say 10,000, the 9 and 10 terms become insignificant.

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-138

Time Analysis
Worst Case, Best Case and Most Likely Case t = (wc + 4*ml + bc) / 6 Example: Worst case Best case Most Likely = 40 ms = 10 ms = 16ms

Expected time = [40 + (4*16) + 10]/6 Expected time = [40 + 64 + 10]/6 Expected time = [114]/6 Expected time = 19 ms

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-139

Big O, Algorithm Analysis


Here is a list of classes of functions that are commonly encountered when analyzing algorithms. All of these are as n increases to infinity. The slower-growing functions are listed first. c is an arbitrary constant

Big O Notation discussion was an excerpt from Data Structures Using Java by D.S. Malik and P. S. Nair, pages 11-15 (2003) Also found on Wikipedia
SLIDE-140

December 30, 2006

Copyright 2004-2007, Jim Adams

Big O, Algorithm Analysis


Graph of Big O Functions
100 90 80 70 60

n2

n log n

log n n n log n n sqr

50 40 30 20 10 0 n

n log n
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-141

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-142

Software Testing
Software Testability
Operability
The better it works, the more efficiently it can be tested

Observability
Bad output is easily found. Source code is accessible

Controllability
Ideally, tests can be specified, automated and reproduced

Decomposability
The software should be built from independent modules so testing can be done independently

Simplicity
The less there is to test, the quicker we can test it

Stability
Software recovers quickly and easily after a failure

Understandability
Source code is well commented, documented, and organized
December 30, 2006 Copyright 2004-2007, Jim Adams SLIDE-143

Unit Test

Test your classes in isolation, outside the program in which they are used Test one class at a time Supply test inputs through a Test Harness A Test Harness is a program that feeds test inputs to a class

Sometimes called a Driver Class


Test Harness

Class To Be Tested

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-144

Test Harness Example


public static void main(String[] args) { sequentialTest1(); sequentialTest2(); sequentialTest3(); indexedTest1(); indexedTest2(); indexedTest3(); indexedTest4(); indexedTest5(); indexedTest6(); indexedTest7(); relativeTest1(); relativeTest2(); relativeTest3(); relativeTest4(); relativeTest5(); miscellaneousTest1(); miscellaneousTests2(); test1Append(); test1Create(); System.exit(0); } // end of main

From an application I wrote last year I created a series of tests that could be run selectively or all in a sequence

private static void indexedTest2() { AdvancedIO T1 = new AdvancedIO("C:TestFile_02","Indexed"); int status = T1.open("A"); if (status == SUCCESSFUL_IO) { System.out.println(T1.getIOStatus()); T1.append(record6[0], record6); T1.append(record6[0], record6); // duplicate key test. T1.append(record7[0], record7); T1.append(record8[0], record8); T1.append(record9[0], record9); T1.close(); } else { System.out.println("Index File Open Status:" + status); } }

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-145

Test Case Evaluation


How do we know the output is correct?

Create a test harness that invokes your classes with known sets of data and compare the results Use a calculator and compare results manually Say you wrote a class to compute approximate square roots

You can feed some known values, say 4 and 100, knowing the answer will be 2 and 10

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-146

Test Cases

Positive test case: expect positive outcome Example: square root of 100 Negative test case: expect the program to reject these cases. Example: square root of -1 or square root of the letter Q Boundary test case: at boundary of domain Frequent cause for errors i.e. square root of 0

This is used a lot when we have arrays of data

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-147

Test Case Evaluation

Manual Run the program over and over entering data manually Check property of result Example: the square root squared = original value Oracle = slower way of computing answer Example. square root of x = x1/2

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-148

Regression Testing
Save test cases to automate future testing java Program < test1.in > test1.out java Program < test2.in > test2.out java Program < test3.in > test3.out Repeat test whenever your program changes Test suite = collection of test cases Cycling = bug that is fixed but reappears in later versions Regression testing = testing against past failures

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-149

Test Coverage
Black-box testing: test functionality without understanding internal structure White-box testing: take internal structure into account when designing tests Performance testing Test coverage: the code that is actually executed during test cases Red Team Test: Hacking teams that try to break the code also called penetration testing. Red team groups develop mock attacks against critical infrastructures and other assets in order to understand events, improve systems, prioritize mitigation, and provide actionable information for decision makers. Regression Testing: Complete test from start to finish of the entire application Easy to overlook error branches during testing Make sure to execute each branch in at least one test case
December 30, 2006 Copyright 2004-2007, Jim Adams SLIDE-150

Program Trace
Output statements in your program for diagnostic purposes
if (status == SINGLE) { System.out.println("status is SINGLE"); ... } Or if (DEBUGGING) // DEBUGGING is a boolean variable { System.out.println(some_variable); }

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-151

Program Trace
Stack trace tells you the contents of the call stack
Throwable t = new Throwable(); t.printStackTrace(System.out);

Looks like exception report in DOS:


java.lang.Throwable at TaxReturn.getTax(TaxReturn.java:26) at TaxReturnTest.main(TaxReturnTest.java:30)

Drawback of trace messages: Need to remove them when testing is complete, stick them back in when another error is found

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-152

Logging
Get global logger object from java.util.*:
Logger logger = Logger.getLogger("global");

Log a message
logger.info("status is SINGLE");

By default, logged messages are printed. Turn them off with


logger.setLevel(Level.OFF);

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-153

The Debugger
Debugger = program to run your program, interrupt it, and inspect variables Three key commands:
Set Breakpoint Single Step Inspect Variable

Two variations of Single Step


Step Over = don't enter method call Step Inside = enter method call
December 30, 2006 Copyright 2004-2007, Jim Adams SLIDE-154

The Debugger Stopping at a Breakpoint

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-155

Inspecting Variables

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-156

Debugging Techniques
Reproduce the error Simplify the error Divide and conquer Know what the program should do Look at all the details Make sure you understand the implication of each change before you make it Dont make arbitrary changes

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-157

Summary
1.

2. 3. 4. 5. 6. 7.

Design Methodologies Software Engineering Processes Software Development Phases Specification and Design Methodologies Implementation of Software Applications Software Failure Method Timing

References http://www.agilemodeling.com/essay s/agileSoftwareDevelopment.htm

Software Engineering, Sixth Edition by Roger Pressman Software Engineering Volume 1: The Development Process. IEEE Press.
UML Excerpts from http://pigseye.kennesaw.edu/~dbraun/csis4 650/A&D/UML_tutorial/activity.htm

Further Research Use Cases UML Diagrams Extreme Programming SDLC Waterfall Methodology Spiral Model Concurrent Development Model Aspect Oriented Software Development Agile Development Navigation Analysis Systems Theory
December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-158

Java Arrays, Array Lists and the Collection Class


1. 2. 3. 4. 5. 6. Learn about common array algorithms Arrays Array lists Single and multi-dimensional arrays Collections Class Java Vectors

Java Arrays
An array is used to process a collection of data with the same data type. Examples List of test scores or temperatures List of names or addresses List of objects
Declaring and Creating an Array int score[] = new int[5]; Same As: int score1; int score2; int score3; int score4; int score5;
December 30, 2006 Copyright 2004-2007, Jim Adams SLIDE-160

Java Arrays
Structured way to store many of similar typed variables or objects Index through the array starting with zero Arrays must be declared with some predetermined size Arrays can store numbers, strings and objects Arrays can be single dimension or multi dimension
December 30, 2006 Copyright 2004-2007, Jim Adams SLIDE-161

Java Arrays
Array types are the second kind of reference types in Java. An array is an ordered collection, or numbered list, of values. The values can be primitive values, objects, or even other arrays, but all of the values in an array must be of the same type. The type of the array is the type of the values it holds, followed by the characters []. For example:
byte b; byte[] arrayOfBytes; byte[][] arrayOfArrayOfBytes; Point[] points; // // // // byte is a primitive type byte[] is an array of byte byte[][] is an array of byte[] Point[] is an array of Point objects

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-162

Declaring Arrays
Declaring and Creating an Array in Java
int junk[] float arr1[] char arr2[] string names[] = = = = new new new new int[200]; float[2000]; char[40]; string[20000];

JComboBox boxes[] = new JComboBox[25]; JMenuItems menuItems[] = new JMenuItems[50]; Object obj[] = new Object[61];
Getting the length of an array or array list
Arrays Array Lists Strings arr.length arr.size() arr.length()

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-163

Declaring Arrays

Declaring and Initializing an Array


int scores[] = {78,87,98,99,12,34,555,654,1,-22}; String vowels[] = {"A", "E", "I", "O", "U"};

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-164

Declaring Arrays
Declaring a Java Array
int scores[] scores[5]; = new int[5]; // index out of bounds // Java compiler will not detect // causes runtime error

index = 12; scores[index];

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-165

Java Arrays
int counts[5] = {2,4,6,8,10}; int i = 1000; for (i=0; i<=5; i++) counts[i]=0; // causes runtime error when i=5 // Throws ArrayIndexOutOfBoundsException

Before -

0th 2 0th 0

1st 4 1st 0

2nd 6 2nd 0

3rd 8 3rd 0

4th 10 4th 0

i variable 1000 0 i variable 1000 0

After -

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-166

Java Arrays
String[] responses = new String[2]; responses[0] = "Yes"; responses[1] = "No"; // Create an array of two strings // Set the first element of the array // Set the second element of the array

// Now read these array elements System.out.println(responses[0] + "/" + responses[1]);

The fact that Java does all array initialization at runtime means that the elements of an array literal can be expressions that are computed at runtime:
Point[] points = { circle1.getCenterPoint(), circle2.getCenterPoint() };

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-167

Java Arrays
int[] perfectNumbers = {6, 28};

This is compiled into Java byte codes that are equivalent to:
int[] perfectNumbers perfectNumbers[0] perfectNumbers[1] = new int[2]; = 6; = 28;

So, if you want to include a large amount of data in a Java program, it may not be a good idea to include that data literally in an array, since the Java compiler has to create lots of Java byte codes to initialize the array, and then the Java interpreter has to execute all that initialization code

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-168

Multi-Dimensional Arrays
Type name[][]. . . . .
double accounts[][] = new accounts[5][50]; double weather[][][] = new weather[100][200][500]; int antenna[][][][] = new antenna[20][20][20][20]; if (antenna[5][6][z][w] == 100) . . .

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-169

Multi-Dimensional Arrays
int[][] products = { {0, {0, {0, {0, {0,
byte arrayOfBytes[]; byte arrayOfArrayOfBytes[][]; byte[] arrayOfArrayOfBytes[];

0, 1, 2, 3, 4,

0, 2, 4, 6, 8,

0, 0}, 3, 4}, 6, 8}, 9, 12}, 12, 16}

};

// Same as byte[] arrayOfBytes // Same as byte[][] arrayOfArrayOfBytes // Yuk! Same as byte[][] arrayOfArrayOfBytes

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-170

Multi-Dimensional Arrays
When you create a multidimensional array using the new keyword, you always get a rectangular array: one in which all the array values for a given dimension have the same size. This is perfect for rectangular data structures, such as matrixes. Because multidimensional arrays are implemented as arrays of arrays in Java, you are in no way constrained to use rectangular arrays. For example, since our multiplication table is symmetrical about the diagonal from top left to bottom right, we can represent the same information in a nonrectangular array with fewer elements:

int[][] products = { {0}, {0, 1}, {0, 2, 4}, {0, 3, 6, 9}, {0, 4, 8, 12, 16} };

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-171

Copying Arrays

System.arraycopy(from, fromStart, to, toStart, count);

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-172

Expanding an Array

double newData = new double[2 * data.length]; System.arraycopy(data, 0, newData, 0, data.length); data = newData;

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-173

The Java Array List


An array list is a sequence of objects Each object in an array list has an integer position number called an index Position numbers range in size from 0 to size()-1 An Array List is a class that allows adding, removing, getting and setting with no upper bounds Array lists store objects only

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-174

Defining a Java Array List


An array list is a sequence of objects Each object in an array list has an integer position number called an index Position numbers range in size from 0 to size()-1 2 forms for adding data

ArrayList arr = new ArrayList(); arr.add( Dave ); arr.add( Tom ); arr.add( Steve ); arr.add(0, Sally ); arr.add(1, Danny );
// or you can use an index

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-175

Array List Methods


arr.add(object); arr.add(index, object); arr.set(index, value); arr.remove(index); arr.contains(value); //returns true/false arr.indexOf(value); //returns index or 1 arr.clear(); // clear the entire arraylist arr.get();

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-176

Array List Methods


If you know in advance how many elements an ArrayList will contain, you can call ensureCapacity(), which can increase efficiency by avoiding incremental reallocation of the internal array You can also pass an initial capacity value to the ArrayList() constructor Finally, if an ArrayList has reached its final size and will not change in the future, you can call trimToSize() to reallocate the internal array with a capacity that matches the list size exactly

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-177

Array List Techniques Using Collections


import java.util.Collections; ArrayList arr = new ArrayList(); .. Add some data to arr
Collections.sort(arr); Collections.shuffle(arr); Collections.reverse(arr); Collections.rotate(arr, n); Collections.swap(arr, x, y); Collections.replaceAll(arr, old value, new value); Collections.min(arr); Collections.max(arr); Collections.binarySearch(arr, value);

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-178

Array List Example (1 of 3)


import java.util.ArrayList; import java.util.Collections; import java.util.logging.Logger; public class ArrayLists { ArrayList arr = new ArrayList(); public ArrayLists() { arr.add("Jimmy"); arr.add("Carlton"); arr.add("Tom"); arr.add("Brian"); arr.add("Manny"); arr.add("Dan"); arr.add("John"); arr.add("Aaron"); arr.add(1, "Evan"); arr.add(5, "Suzie"); arr.add("Sally"); arr.add("Betty"); arr.add("Lucy"); arr.set(0, "Jim"); arr.set(3, "Tommy"); System.out.println(arr.indexOf("Tommy")); arr.remove(3); System.out.println(arr.indexOf("Tommy")); December 30, 2006 // // returns -1. No Find SLIDE-179 // specific location // specific location

Copyright 2004-2007, Jim Adams

Array List Example (2 of 3)


dump("Original Data"); Collections.sort(arr); dump("Sorted Data"); Collections.shuffle(arr); dump("Shuffled"); Collections.sort(arr); dump("Sorted"); Collections.reverse(arr); dump("Reversed"); Collections.sort(arr); dump("Sorted Data"); } private void dump(String header) { System.out.println(" =====" + header + "====="); System.out.println(arr); } // end of class

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-180

Output From Previous Program (3 of 3)


3 -1 =====Original Data===== [Jim, Evan, Carlton, Brian, Suzie, Manny, Dan, John, Aaron, Sally, Betty, Lucy] =====Sorted Data===== [Aaron, Betty, Brian, Carlton, Dan, Evan, Jim, John, Lucy, Manny, Sally, Suzie] =====Shuffled===== [Aaron, Sally, Dan, John, Suzie, Jim, Brian, Evan, Lucy, Betty, Manny, Carlton] =====Sorted===== [Aaron, Betty, Brian, Carlton, Dan, Evan, Jim, John, Lucy, Manny, Sally, Suzie] =====Reversed===== [Suzie, Sally, Manny, Lucy, John, Jim, Evan, Dan, Carlton, Brian, Betty, Aaron] =====Sorted Data===== [Aaron, Betty, Brian, Carlton, Dan, Evan, Jim, John, Lucy, Manny, Sally, Suzie]

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-181

Java Vector Class


Vectors are expanded as an element is added Can be expensive but it is convenient
Vector v = new Vector(15); Integer j = null; int i; for (i = 0; i < 10; i++) { j = new Integer((int) (Math.random() * 100)); v.addElement(j); System.out.println("addElement: " + j); } System.out.println("size: " + v.size()); System.out.println("capacity: " + v.capacity());
addElement: 9 addElement: 5 addElement: 54 addElement: 49 addElement: 60 addElement: 81 addElement: 8 addElement: 91 addElement: 76 addElement: 81 size: 10 capacity: 15 enum: 9 enum: 5 enum: 54 enum: 49 enum: 60 enum: 81 enum: 8 enum: 91 enum: 76 enum: 81

Enumeration enumx = v.elements(); while (enumx.hasMoreElements()) { System.out.println("enumx: " + (Integer) enumx.nextElement()); }

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-182

Summary
Arrays Array Lists Vector Class Collection Class
Material extracted from: Data Structures and the Java Collections Framework, 2nd Ed. William Collins Data Structures and Other Objects, 2nd Ed. by Michael Main

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-183

Java File I/O


Chapter Goals
1. 2. 3.

Concepts of text and binary formats Read and write objects Sequential and random file access

Streams, Readers and Writers


Two fundamentally different ways to store data: text or binary. Text format is a human readable format
1, 2, 3, 4, 5, takes five bytes 49 50 51 52 53, in base-10 31 32 33 34 35, in hex

Binary format is a series of bytes more efficient for the computer to process
00 00 48 57 in base-10 00 00 30 39 in hex 0000 0000 0000 0000 0011 0000 0011 1001

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-185

Streams, Readers and Writers


To read text files we use the FileReader object
FileReader reader = new FileReader(mytextfile.txt);

To read binary files we use the FileInputStream object


FileInputStream input =
new FileInputStream(mybinarydata.dat);

Found in java.io package

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-186

Streams, Readers and Writers


Read a text file one character at a time
import java.io.*; class Tester { public static void main(String[] args) throws IOException { int next; char ch; boolean done=false; final int EOF = -1; FileReader r = new FileReader("Tester.java"); while (!done) { next = r.read(); if (next == EOF) { done=true; } else { ch = (char) next; System.out.print(ch); } // end of if } // end of while } // end of main } // end of class
December 30, 2006 Copyright 2004-2007, Jim Adams SLIDE-187

Streams, Readers and Writers


Read a binary file one byte at a time
import java.io.*; class Tester { public static void main(String[] args) throws IOException { int next; char ch; byte b; boolean done=false; final int EOF = -1; FileInputStream s = new FileInputStream("Tester.java"); while (!done) { next = s.read(); if (next == EOF) done=true; else { b = (byte) next; System.out.print(b); } }

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-188

Streams, Readers and Writers


To write text files we use the FileWriter object
FileWriter writer = new FileWriter(out.txt);

To write binary files we use the FileOutputStream object


FileOutputStream output = new FileOuputStream(out.dat);

Found in java.io package

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-189

Streams, Readers and Writers


1. 2. 3. 4.

Streams access sequences of bytes Readers and writers access sequences of characters They process individual bytes and characters only Must use other classes and methods to process entire objects or lines of data

Use FileReader and FileWriter to read and write text files Use FileInputStream and FileOutputStream to read and write binary files

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-190

Streams, Readers and Writers


writer.close() Why Close a file? Input Files Frees the file for others to use Generally a file is opened for exclusive use unless forced to share Output Files Writes the last cached output to disk
December 30, 2006 Copyright 2004-2007, Jim Adams SLIDE-191

Common Error
Using the back slash in a file name
FileInputStream in = new FileInputStream(C:\\homework\\csc205\\pg1.java);

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-192

Common Error
Negative byte values
class Tester2 { public static void main(String[] args) { int n = 233; // binary 00000000 00000000 00000000 11101001 byte b = (byte) n; // binary 11101001, with sign bit set = -105 if (b != n) { System.out.println("Not Equal"); } System.out.println(n); System.out.println(b); } }

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-193

Reading and Writing Text Files


Construct a PrintWriter class from any writer object
FileWriter writer = new FileWriter("Output.txt"); PrintWriter fout = new PrintWriter(writer);
import java.io.*; class Tester { public static void main(String[] args) throws IOException { double cost=12345.55; FileWriter writer = new FileWriter("Output.txt"); PrintWriter fout = new PrintWriter(writer); fout.println("Hey Dude"); fout.println(cost); fout.close(); } }
December 30, 2006 Copyright 2004-2007, Jim Adams SLIDE-194

Reading and Writing Text Files


Reading Buffered Input
import java.io.*; class Tester3 { public static void main(String[] args) throws IOException { double x; String inputline; FileReader reader = new FileReader("Output.txt"); BufferedReader in = new BufferedReader(reader); inputline = in.readLine(); System.out.println(inputline); inputline = in.readLine(); x = Double.parseDouble(inputline); System.out.println(x); in.close(); } }
December 30, 2006 Copyright 2004-2007, Jim Adams SLIDE-195

Object Streams
We can also read and write entire objects We use ObjectOutputStream and ObjectInputStream Objects are stored in binary format therefore we use streams not writers
Coin c = new Coin(); ObjectOutputStream out = new ObjectOutputStream(coins.dat); out.writeObject(c); Coin c = new Coin(); ObjectInputStream in = new ObjectInputStream(coins.dat); Coin c = in.readObject();

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-196

Random Access
Most data in the business world is comprised of records. Records are sets of related information
1. 2. 3. 4. 5. 6.

Databases contain sets of related files Files contain records Records contain fields Fields contain characters (bytes) Bytes are made up of bits Bits

Think of a File Cabinet (Database) Contains Drawers (Files) Contains Folders (Records) We generally want to gain access to specific records in an arbitrary manner. We introduce Random Access files

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-197

Random Access
So far we have simply used sequential access Reading bytes from start until we reach the end of a file Each file has a file pointer that points to the current position in the file Upon opening a file, the position is 0 RandomAccessFile is the random access class Works on fixed length records Can be a fixed length of one, if necessary
File Name File Mode

long n; long filelength;

RandomAccessFile f = new f.seek(n); n = f.getFilePointer(); filelength=f.length();


December 30, 2006

RandomAccessFile(bank.dat, rw); // moves file pointer to byte n // get current file pointer in n // get the file length in bytes
Copyright 2004-2007, Jim Adams SLIDE-198

Random Access
import java.io.*; class RandomAccess { public static void main(String[] args) throws IOException { long n; long filelength; byte ch; RandomAccessFile f = new RandomAccessFile("Tester.java", "r"); n = f.getFilePointer(); filelength=f.length(); // get current file pointer in n // get the file length in bytes

for (n=0; n<20; n++) { f.seek(n); ch = f.readByte(); // read a byte System.out.println((char) ch); } System.out.println(filelength); // display the file length } }
SLIDE-199

December 30, 2006

Copyright 2004-2007, Jim Adams

File Dialogs
JFileChooser Lets user navigate through their directories and select a file Relies on another class named File File inputfile = new File(input.txt); Key Elements

import java.io.*; import javax.swing.JFileChooser; JFileChooser chooser = new JFileChooser(); FileReader in = null; File selectedFile = chooser.getSelectedFile(); in = new FileReader(selectedFile);

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-200

File Dialogs
import java.io.*; import javax.swing.JFileChooser; class Tester4 { public static void main(String[] args) throws IOException { char ch; int next; boolean done=false; String inputline; JFileChooser chooser = new JFileChooser(); FileReader in = null; if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) { File selectedFile = chooser.getSelectedFile(); in = new FileReader(selectedFile); } while (!done) { next = in.read(); if (next == -1) done=true; else { ch = (char) next; System.out.print(ch); } }
Copyright 2004-2007, Jim Adams SLIDE-201

} // end of class

December 30, 2006

Java File I/O Summary


1. 2. 3. 4. 5. 6. 7. 8.

Streams use sequences of bytes Readers and writers access characters Use FileReader and FileWriter to access characters Use FileInputStream and FileOutputStream to access bytes Use JFileChooser to let the user select a file Random access can read and and write records A file pointer is a position in a random access file Sequential access files are process serially

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-202

Students learn best when they practice every day and when they teach others

Recursion Programming
What it is How to do it Examples

Introduction
o

Recursion is a powerful programming technique that provides elegant solutions to certain problems. Recursion is a programming technique in which a method calls itself either directly, or indirectly through another method. Where is recursion used?
o o o o o

File and Directory Searches Traveling Salesman Problems Shortest Route Problems Mathematical Series Types of Problems Sorting and Searching

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-204

Overview
o

AT ONE TIME OR ANOTHER, you've probably been told that you can't define something in terms of itself. Nevertheless, if it's done right, defining something at least partially in terms of itself can be a very powerful technique. A recursive definition is one that uses the concept or thing that is being defined as part of the definition. An "ancestor" is either a parent or an ancestor of a parent. A "sentence" can be, among other things, two sentences joined by a conjunction such as "and." A "directory" is a part of a disk drive that can hold files and directories. In mathematics, a "set" is a collection of elements, which can be other sets. A "statement" in Java can be a while statement, which is made up of the word "while", a boolean-valued condition, and a statement.
SLIDE-205

o o

o o

December 30, 2006

Copyright 2004-2007, Jim Adams

Simple Example 1
public static void main(String[] args) { myMethod1(20); } static void myMethod1(int counter) { if(counter == 0) return; else { System.out.println(counter); myMethod1(--counter); return; } } // end myMethod }
20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-206

Simple Example 2
public static void main(String[] args) { myMethod2(20); } static void myMethod2( int counter) { if(counter == 0) return; else { System.out.println("hello" + counter); myMethod2(--counter); System.out.println(goodbye + counter); return; } } // end of method } // end of main
December 30, 2006 Copyright 2004-2007, Jim Adams

hello20 hello19 hello18 hello17 hello16 hello15 hello14 hello13 hello12 hello11 hello10 hello9 hello8 hello7 hello6 hello5 hello4 hello3 hello2 hello1 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
SLIDE-207

A Mathematical Example Factorials


o

Mathematical formulas often are expressed recursively. In the following example, we will look in depth at factorials.

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-208

Definition of Factorial
Factorials - ! The symbol for factorial is ! - the exclamation mark. The factorial of a positive integer is the product of all nonnegative integers less than or equal to that number. Zero factorial is a special case and 0! = 1 From this definition, 5! is 120. 5! = 5 . 4 . 3 . 2 . 1 = 120 This formula often is defined recursively, for all nonnegative integers as: n! = n(n-1)! for n > 0; 0! = 1; Any number factorial is that number times the factorial of one less than that number.
December 30, 2006 Copyright 2004-2007, Jim Adams SLIDE-209

A Closer Look
Now, lets look at the expression,
n! = n * (n-1)! for n > 0; 0! = 1

You will notice that n! subtracts 1 from n, then recomputes the factorial of n-1. This is the recursion. Also notice that the simplest case is 0! This is called the base case.
December 30, 2006 Copyright 2004-2007, Jim Adams SLIDE-210

Factorial using Recursion


public class Recur { public static void main(String[] args) { System.out.println(factorial(6)); } private static long factorial(long num) { if (num == 0) // base case return (1); return (num * factorial(num - 1)); } } Each recursive call to a method produces a new set of local variables and parameters
December 30, 2006 Copyright 2004-2007, Jim Adams SLIDE-211

Base Cases
Base cases are important. A recursive method can solve only a base case. If the method is called with a base case, it returns a result. If the methods is called with something other than the base case, the recursive method will decide what part it can accomplish, and then call itself to solve the rest of the problem.

o o

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-212

Linear Recursion
o

Linear recursion is the simplest form of recursion. It occurs where an action has a simple repetitive structure consisting of some basic step followed by the action again.

procedure ODSN begin One dark and stormy night, Three men sat in a cave, And one said to another, Dick, tell us a tale, And this is how the tale began: ODSN -- again! end
December 30, 2006 Copyright 2004-2007, Jim Adams SLIDE-213

Linear Recursion
This simple tale has amused generations of small children precisely because it is so simple but never ends. It seems somehow paradoxical. Generally we want the recursion to terminate on some condition. The song `Ten Green Bottles' does not go on forever:

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-214

Linear Recursion
Ten Green Bottles
10 green bottles hanging on the wall, 10 green bottles hanging on the wall, And if 1 green bottle should accidentally fall, There'll be 9 green bottles hanging on the wall. 9 green bottles hanging on the wall, 9 green bottles hanging on the wall, And if 1 green bottle should accidentally fall, There'll be 8 green bottles hanging on the wall. .... 2 green bottles hanging on the wall, 2 green bottles hanging on the wall, And if 1 green bottle should accidentally fall, There'll be 1 green bottle hanging on the wall. 1 green bottle hanging on the wall, 1 green bottle hanging on the wall, And if 1 green bottle should accidentally fall, There'll be 0 green bottles hanging on the wall.
SLIDE-215

December 30, 2006

Copyright 2004-2007, Jim Adams

Linear Recursion

This illustrates the power of recursion nicely. The routine worries not so much about the whole song as about the basic step, one verse. It calls itself to generate the rest of the song. Note the terminating condition, i.e. the base case (n<=0) and test for it. The parameter `n' is decreasing in the recursive calls `verse(n-1)' so eventually n reaches zero, and the program terminates.

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-216

Recursion
o

Handle the base cases first.


You already know that a recursive routine must have some base cases, cases that it can compute directly without the need for recursion. The very first thing you should do upon entry to a recursive routine is to test whether you have a base case, and if you do, do whatever needs to be done for that case and return. Don't mess around, and don't recur, just do what needs to be done and get out.

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-217

Binary Searching
static int binarySearch(int[] A, int loIndex, int hiIndex, int value) { // Search in the array A in positions from loIndex to hiIndex, // inclusive, for the specified value. It is assumed that the // array is sorted into increasing order. If the value is // found, return the index in the array where it occurs. // If the value is not found, return -1. if (loIndex > hiIndex) { // The starting position comes after the final index, // so there are actually no elements in the specified // range. The value does not occur in this empty list! return -1; } else { // Look at the middle position in the list. If the // value occurs at that position, return that position. // Otherwise, search recursively in either the first // half or the second half of the list. int middle = (loIndex + hiIndex) / 2; if (value == A[middle]) return middle; else if (value < A[middle]) return binarySearch(A, loIndex, middle - 1, value); else // value must be > A[middle] return binarySearch(A, middle + 1, hiIndex, value); } } // end binarySearch()
December 30, 2006 Copyright 2004-2007, Jim Adams SLIDE-218

Recursive Directory Searching


private void get_dir(String dir_in) { try { File directory = new File(dir_in); File[] files = directory.listFiles(); if (files == null) return; // base case

} catch (Exception ex) { } }

for (int i=0; i<files.length; i++) { if (files[i].isDirectory()) { get_dir(files[i].toString()); } else { System.out.println(files[i]); } }

Needs: import java.io.*;


SLIDE-219

December 30, 2006

Copyright 2004-2007, Jim Adams

Pascals Triangle
for(int i=0; i< 10; i++) { for(int j=0; j <=i; j++) System.out.println(); }
1 11 121 14641 1 5 10 10 5 1 1 6 15 20 15 6 1

System.out.print(pascal(i,j)+" "); 1 3 3 1

public static long pascal (int n, int k) 1 7 21 35 35 21 7 1 { if (k == 0 || k == n) return 1; else return pascal(n-1,k-1) + pascal(n-1,k); }
December 30, 2006 Copyright 2004-2007, Jim Adams

1 8 28 56 70 56 28 8 1 1 9 36 84 126 126 84 36 9 1

SLIDE-220

Reverse a String
public static void ReverseString(String s) { if (s.length() == 1) System.out.print(s); else { ReverseString(s.substring(1)); System.out.print(s.charAt(0)); } }

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-221

Summary
o

Recursion is a powerful programming technique that provides elegant solutions to certain problems. Recursion is a technique in which a method calls itself either directly, or indirectly through another method. Base cases are usually the simplest cases a recursive method can solve. Recursion is Difficult to Master Recursion yields elegant and concise code Yet, it is difficult to debug

o o o

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-222

Java Linked Lists


Objectives To learn how to use linked lists provided in the standard library To be able to use iterators to transverse linked lists To understand the implementation of linked lists To distinguish between abstract and concrete data types To know the efficiency of fundamental operations of lists and arrays How we will learn this topic
Discuss theory Show Java functions that relate to the theory Look at an example or two Do the homework to reinforce the theory

The Collection Classes


Collection Classes
AbstractCollection AbstractList AbstractSequentialList LinkedList ArrayList AbstractSet HashSet TreeSet AbstractMap HashMap TreeMap WeakHashMap
December 30, 2006 Copyright 2004-2007, Jim Adams SLIDE-224

Linked Lists
A linked list consists of a number of links, each of which has a reference to the next link Adding and removing elements in the middle of a linked list is efficient Visiting the elements of a linked list in sequential order is efficient Random access is not efficient

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-225

Linked Lists
Some common examples of a linked list: Hash tables use linked lists for collision resolution Any "File Requester" dialog uses a linked list Binary Trees Stacks and Queues can be implemented with a doubly linked list Relational Databases

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-226

A Doubly Linked List

1. 2.

Each object points to the next one Each object points to the previous one, as well

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-227

Adding an Element to a Linked List

1. 2. 3.

Get the address of both sides of the location you want to add Allocate a new object Adjust the pointers

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-228

Deleting An Object from a Linked List

1. 2.

Easier than adding Simply Point around the object to be deleted

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-229

Managing a Sorted Linked List

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-230

Linked Lists in Java


Two ways to manage linked lists in Java:
1. The "old school" way Uses the implicit reference to an object as the link Write all the methods to, add, delete, insert and traverse Use Java's built-in methods of the LinkedList class Built-in, ready made methods to add, delete, and traverse a linked list

2.

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-231

Linked List Example (1 of 2)


public class LinkedList_Test { Node node = null; Node head = null; public LinkedList_Test() { head = new Node(900, null); node = head; for (int i = 1; i < 10; i++) add(i, node);
public class Node { private int value; private Node next; public Node(int value_in, Node n) { this.value = value_in; this.next = n; } }

Node p = node; while (p != null) { System.out.println(p.value + " | " + p.next); p = p.next; } Node h = head; System.out.println("Head Value:" + h.value); System.out.println("Head Pointer:" + h.next);

private void add(int value, Node n) { node = new Node(value, n); }


SLIDE-232

December 30, 2006

Copyright 2004-2007, Jim Adams

Linked List Example (2 of 2)


public class Node { private int value; // value of element private Node next; // reference to next node public Node(int value_in, Node n) { this.value = value_in; this.next = n; } } Generated Output 9 | csc263_stuff.LinkedList_Simulator$Node@eee36c 8 | csc263_stuff.LinkedList_Simulator$Node@194df86 7 | csc263_stuff.LinkedList_Simulator$Node@defa1a 6 | csc263_stuff.LinkedList_Simulator$Node@f5da06 5 | csc263_stuff.LinkedList_Simulator$Node@bd0108 4 | csc263_stuff.LinkedList_Simulator$Node@8ed465 3 | csc263_stuff.LinkedList_Simulator$Node@11a698a 2 | csc263_stuff.LinkedList_Simulator$Node@107077e 1 | csc263_stuff.LinkedList_Simulator$Node@7ced01 900 | null Head Value:900 Head Pointer:null

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-233

Managing a Linked List


Adding a new node to the head of a list head = new Node(value, head); Removing a node to the head of a list head = head.getLink(); Adding a new node that is not at the head of the list Selection.addNodeAfter(current_element); link = new Node(current_node, link); Removing a new node that is not at the head of a list Selection.removeNodeAfter(); link = link.link;

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-234

Managing a Linked List


How does all this work?
Every time you instantiate a new object there is an implicit reference to it Null
900 Node node = null; node = new Node(900, null); node = new Node(800, node); node = new Node(700, node); Null 900 Null 900 800 800 700

public class Node { private int value; // value of element private Node next; // reference to next node public Node(int value_in, Node n) { this.value = value_in; this.next = n; }
December 30, 2006 Copyright 2004-2007, Jim Adams SLIDE-235

The Java LinkedList Class


java.lang.Object java.util.AbstractCollection java.util.AbstractList java.util.AbstractSequentialList java.util.LinkedList Constructors
LinkedList() LinkedList(Collection c) Constructs a Linked List Constructs a list containing an existing collection

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-236

Java's Linked List Class


Java makes it extremely easy to create and manipulate linked lists Many methods for navigation of linked lists Easy access to first and last elements with methods

Java Linked List Methods


void add(Object) // add to end of list void add(int index, Object) // add at specified index void addFirst(Object obj) void addLast(Object obj) Object getFirst() Object getLast() Object get(int index) //gets object at specified index Object removeFirst() Object removeLast() Object remove(int index) // remove object at index Object remove(Object) // remove object boolean contains(Object) // returns true if object exists int indexOf(Object) // returns the index of an object int lastIndexOf(Object) // returns the last index of an object int size() Object set(int index, Object)

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-237

Iterator Interface
The Iterator Interface gives access to elements inside a linked list Used for moving forward through a linked list
LinkedList list = new LinkedList(); Iterator iterator = list.iterator();

The Iterator method of the LinkedList class gets an iterator


Iterator methods: Object.next() Object.hasNext() Object.remove() while (iterator.hasNext()) System.out.println(iterator.next());
December 30, 2006 Copyright 2004-2007, Jim Adams SLIDE-238

List Iterator Interface


The ListIterator Interface gives backwards access to elements inside a linked list Can move forward or backward in a linked list
LinkedList list = new LinkedList(); ListIterator iterator = list.listIterator(); The listIterator method of the LinkedList class gets a list iterator List Iterator methods:
Object.add() Object.hasNext() Object.hasPrevious() Object.next() Object.previous() Object.remove() Object.set()
December 30, 2006 Copyright 2004-2007, Jim Adams SLIDE-239

Conceptual View of the List Iterator

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-240

List Iterator
The next method moves the iterator iterator.next(); next method throws a NoSuchElementException if you are already past the end of the list The hasNext method returns true if there is a next element if (iterator.hasNext()) iterator.next();

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-241

List Iterator
The next method returns the object of the link that it is passing
while (iterator.hasNext()) { Object obj = iterator.next(); //do something with the object }

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-242

List Iterator
To move the list position backwards, use:
hasPrevious previous

while (iterator.hasPrevious()) { Object obj = iterator.previous(); //do something with the object }

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-243

Adding an Object to a Linked List


The add method: Adds an object after the iterator Moves the iterator position past the new element iterator.add("Juliet");

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-244

Removing an Object from a Linked List


The remove method: Removes and Returns the object that was returned by the last call to next or previous This loop removes all objects that fulfill a certain condition while (iterator.hasNext()) { Object obj = iterator.next(); if (obj fulfills condition) iterator.remove(); }

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-245

Adding a New First Element When a new link is added to the list using the addFirst() method
It becomes the head of the list The old first link becomes the next link

The addFirst method


object.addFirst(object);

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-246

Adding a Link to the Head of a Linked List

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-247

Removing the First Element

When the first element is removed


The data of the first link are saved and later returned as the method result The successor of the first link becomes the first link of the shorter list The removed link will be garbage collected when there are no further references to it

The removeFirst method


Object.removeFirst();
December 30, 2006 Copyright 2004-2007, Jim Adams SLIDE-248

Removing the First Link from a Linked List

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-249

import java.util.LinkedList; import java.util.ListIterator;

Linked List Example (1 of 3)

public class LinkList { private String[] names = {"Jamie", "Suzie", "Callie", "Malcholm", "Danny", "Dan", "Roger", "Eric", "Mike", "Will", "Carolyn"}; public LinkList() { LinkedList staff = new LinkedList(); // add a bunch of string objects to the end for (int i = 0; i < names.length; i++) { staff.addLast(names[i]); } // add some string objects to the front staff.addFirst("Sharon"); staff.addFirst("George"); staff.addFirst("Patty"); staff.removeFirst(); staff.removeLast(); printIndexes(staff); printBirthOrder(staff); printReverseOrder(staff);

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-250

Linked List Example (2 of 3)


private void printBirthOrder(LinkedList list) { System.out.println("Printing in birth order"); list.getFirst(); ListIterator iterator = list.listIterator(); while (iterator.hasNext()) { System.out.println(iterator.next()); }

private void printReverseOrder(LinkedList list) { System.out.println("Printing in reverse birth order"); list.getLast(); ListIterator iterator = list.listIterator(); while (iterator.hasPrevious()) { System.out.println(iterator.previous()); } }

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-251

Linked List Example (3 of 3)


private void printIndexes(LinkedList list) { for (int i = 0; i < names.length; i++) { System.out.println(list.lastIndexOf(names[i])); } 2 3 } 4
5 6 7 8 9 10 11 -1 Printing in birth order George Sharon Jamie Suzie Callie Malcholm Danny Dan Roger Eric Mike Will

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-252

Linked List Example (1 of 2)


import java.util.*; public class LinkList { private String[] names = {"Jamie", "Suzie", "Callie", "Malcholm", "Danny", "Dan", "Roger", "Eric", "Mike", "Will", "Carolyn"}; public LinkList() { LinkedList staff = new LinkedList(); for (int i = 0; i < names.length; i++) staff.addLast(names[i]); staff.addFirst("Sharon"); staff.addFirst("George"); staff.addFirst("Patty"); staff.add(3, "Carol"); staff.add(5, "Adrian"); staff.removeFirst(); staff.removeLast(); staff.set(6, "Lloyd"); staff.set(7, "Johhny"); System.out.println("First Node:" + System.out.println(" Last Node:" + } printAll(staff);
SLIDE-253

(String) staff.getFirst() ); (String) staff.getLast() );

December 30, 2006

Copyright 2004-2007, Jim Adams

Linked List Example (2 of 2)


private void printAll(LinkedList list) { System.out.println("Printing Entire Linked List"); for (int i = 0; i < list.size(); i++) { System.out.println(i + ":" + list.get(i).toString()); } } First Node:George
Last Node:Will Printing Entire Linked List 0:George 1:Sharon 2:Carol 3:Jamie 4:Adrian 5:Suzie 6:Lloyd 7:Johhny 8:Danny 9:Dan 10:Roger 11:Eric 12:Mike 13:Will

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-254

Summary

1. 2. 3.

Linked Lists Iterators List Iterators

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-255

Java Stacks and Queues


1. 2.

Stacks Queues

Objectives To become familiar with the stacks and queues

Abstract Data Type -- Stack


The Java Stack class is a concrete implementation of a stack in the Java library A stack can be visualized as a stack of books. You place books on top and remove from the top. The Stack class uses an Object[] to implement a stack

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-257

Abstract Data Type -- Stack


Examples Web browsers store recently used URL's. Each time a user visits a new site the URL is "Pushed" onto a stack Allows the user to "Pop" back to some previous URL Text editors and word processors Undo operations Like the plates at the Country Buffet!! Hundreds of uses inside an Operating System Compilers, too

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-258

Managing a Stack (LIFO Queue)

Always either Adding the First object or Deleting the First Object Called Push and Pop Push one on the stack Pop one off the stack

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-259

Stack Discussion (LIFO Queue)

Stacks are used by the hundreds in computer science, especially operating systems Internal stacks are used to control the return address of method calls

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-260

Stack Discussion
java.lang.Object java.util.AbstractCollection java.util.AbstractList java.util.Vector java.util.Stack Methods of the Java Stack Class boolean empty() Object peek() Object pop() Object push(Object) int search(Object) Returns true if stack is empty Gets the top object, but does not remove it Removes the top object Adds a new object to the top of the stack Gets the position of an object

Excerpt from: Java 2. Black Book by Steven Holzner. p 1015

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-261

Java Stack Class - Example One


Sample code to use the Java Stack class Loop until exception is thrown
import java.util.Stack; public class Stack_Example { public Stack_Example() Stack s = new Stack(); s.push("Alpha"); s.push("Beta"); s.push("Charlie"); s.push("Delta"); s.push("Epsilon"); s.push("Frank"); s.push("Gamma"); s.push("Harry"); Stack Size is:8 Harry Gamma Frank Epsilon Delta Charlie Beta Alpha Whoops. Stack is Empty, Baby

System.out.println("Stack Size is:" + s.size()); try { while(true) System.out.println(s.pop()); } catch (Exception ex) { System.out.println("Whoops. Stack is Empty, Baby"); }

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-262

Java Stack Class - Example Two


Sample code to use the Java Stack class Get length. Loop up to length
import java.util.Stack; public class Stack_Example { public Stack_Example() { Stack s = new Stack(); s.push("Alpha"); s.push("Beta"); s.push("Charlie"); s.push("Delta"); s.push("Epsilon"); s.push("Frank"); s.push("Gamma"); s.push("Harry"); int stack_size=s.size(); System.out.println("Stack Size is:" + stack_size); for (int k=0; k<stack_size; k++) System.out.println(s.pop()); } } Stack Size is:8 Harry Gamma Frank Epsilon Delta Charlie Beta Alpha

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-263

Java Stack Class - Example Three


Sample code to use the Java Stack class Using the Stack class empty() Method
import java.util.Stack; public class Stack_Example { public Stack_Example() { Stack s = new Stack(); s.push("Alpha"); s.push("Beta"); s.push("Charlie"); s.push("Delta"); s.push("Epsilon"); s.push("Frank"); s.push("Gamma"); s.push("Harry"); Stack Size is:8 Harry Gamma Frank Epsilon Delta Charlie Beta Alpha

System.out.println("Stack Size is:" + stack_size); while (! s.empty()) System.out.println(s.pop()); } }

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-264

Java Stack Class - Example Four


Sample code to use the Java Stack class Using the peek() and search() methods
import java.util.Stack; public class Stack_Example { public Stack_Example() { Stack s = new Stack(); s.push("Alpha"); s.push("Beta"); s.push("Charlie"); s.push("Delta"); s.push("Epsilon"); s.push("Frank"); s.push("Gamma"); s.push("Harry");

Harry Stack Size is Now:8 Charlie is at Location:6 1:Harry 2:Gamma 3:Frank 4:Epsilon 5:Delta 6:Charlie 7:Beta 8:Alpha

System.out.println(s.peek()); // look at top value int stack_size=s.size(); System.out.println("Stack Size is Now:" + stack_size); // look at size int loc = s.search("Charlie"); System.out.println("Charlie is at Location:" + loc); int n=1; while (! s.empty()) System.out.println(n++ + ":" + s.pop()); } }

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-265

import java.util.LinkedList; import java.util.ListIterator; import java.util.NoSuchElementException; public class Stack { static LinkedList staff = new LinkedList(); static ListIterator iterator = staff.listIterator(); public static void main(String[] args) { String name; int i; push("Jamie"); push("Suzzy"); push("Callie"); push("Malcholm"); push("Dan"); push("Will"); push("Roger"); push("Eric"); push("Mike"); push("Sharon"); push("George"); push("Patty"); for (i=0; i<15; i++) System.out.println(pop());
December 30, 2006 Copyright 2004-2007, Jim Adams SLIDE-266

Stack Simulation (1 of 2)

Stack Simulation (2 of 2)
// Push an object onto the stack // Passes a string object to place onto the stack // private static void push(String p) { staff.addFirst(p); } // Pop an object off of the stack // Returns a string object from the stack George Sharon // Mike private static String pop() { Eric Object obj=null; Roger String name=""; Will if (iterator.hasNext()) { obj=staff.getFirst(); name = (String) obj; staff.removeFirst(); return(name); } else //throw new NoSuchElementException(); return("End of Stack"); } // end of method
December 30, 2006 Copyright 2004-2007, Jim Adams SLIDE-267

Patty

Dan Malcholm Callie Suzzy Jamie End of Stack End of Stack End of Stack

Expression Parsing
One place where stacks can be useful is in parsing expressions like,

x = {[X+Y*(Z+7)]*(A+B)}
One could write a Java method that returns a boolean

balanced = isBalanced(expression);
Each left brace, parenthesis or bracket causes a push onto a stack structure Each right occurrence causes a pop off the stack.

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-268

Expression Parsing
Using the previous good expression,

x = {[X+Y*(Z+7)]*(A+B)}
we would be doing the following: 1. Push { 2. Push [ 3. Push ( 4. Pop ) 5. Pop ] 6. Push ( 7. Pop ) 8. Pop } Empty Stack means we are balanced

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-269

Expression Parsing
Using the following bad expression,

x = {[X+Y*(Z+7)*(A+B)}
we would be doing the following: 1. Push { 2. Push [ 3. Push ( 4. Pop ) 5. Push ( 6. Pop ) 7. Pop } The Stack is not empty so we must be unbalanced In other words we left something on the stack

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-270

Expression Parsing
Let's look at this fully parenthesized expression, double x = (((6+9)/3)*(6-4)); We need to extract the leftmost of the innermost subexpression (((6+9)/3)*(6-4)) ((15/3)*(6-4)) (5*(6-4)) (5*2) 10 This method works well with paper and pencil, but how do we extract each character?

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-271

Expression Parsing
We need two stacks to parse an expression
1. 2.

A number stack An operator stack

We read up to the first right parenthesis; the numbers we encounter along the way are pushed onto the number stack Operators we encounter along the way are pushed onto the operator stack double x = (((6+9)/3)*(6-4)); When we reach the first right parenthesis we have the following stack situation
9 6
Number Stack

+
Op Stack

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-272

Expression Parsing
Whenever we reach a right parenthesis, we combine the top two numbers on the number stack, using the topmost operator on the operator stack double x = (((6+9)/3)*(6-4)); In our example we combine 6 + 9 to get 15 and push that value onto the number stack, and pop one off the op stack
15
Number Stack Op Stack

Our expression now looks like: ((15/3)*(6-4));


3 15
Number Stack

/
Op Stack

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-273

Expression Parsing
We combine 15 / 3 to get 5 and push that value onto the number stack Our expression now looks like: (5*(6-4))
5
Number Stack Op Stack

We parse out the next two numbers, 6 and 4 and push them onto the number stack Push the minus sign onto the operator stack
4 6 5
Number Stack

*
Op Stack

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-274

Expression Parsing
We combine 6 - 4 to get 2 and push that value onto the number stack Our expression now looks like: (5*2)
2 5
Number Stack

*
Op Stack

Finally, we pop the last two numbers off the stack along with the last operator. Combine them and push the final values back on to the stack

10
Number Stack Op Stack

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-275

Expression Parsing
Issues
(((6+9)/3)*(6-4)); ( ( ( 6 + 9) / 3 ) * ( 6 - 4) ); (((x+y)/q)*(6-w)); ( ( ( x + y) / q ) * ( 6 - w) ); ((( x + y) / q ) * (6 pow(w))); // // // // // numbers only are easy white space variables variables & white space embedded methods

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-276

A Queue

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-277

Abstract Data Type -- Queues


Examples
Direct applications Waiting lists Stores Theater lines Access to shared resources Printer queues Multiprogramming
Disk I/O Thread Queues

Indirect applications Auxiliary data structure for algorithms Component of other data structures

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-278

Abstract Data Type -- Queues


Insertions and deletions follow the first-in first-out scheme (FIFO) Insertions are at the rear of the queue and removals are at the front of the queue Main queue operations: enqueue: inserts an element at the end of the queue dequeue: removes and returns the element a the front of the queue

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-279

Abstract Data Type -- Queue


Items added to one end of the queue (the tail) Items removed from the other end (the head) Called first in, first out or FIFO order A Queue can be visualized as a queue of people. People join the tail of the queue and wait until they reach the head.

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-280

Managing a Queue (FIFO)

Always either Adding the First object or Deleting the Last Object Like the Check-out Lines at the Home Depot

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-281

FIFO Queue Discussion

Java is excellent for simulation of queued processes Supermarket checkout lines Printer queues on LANs The list is almost endless Point to consider: 1. Create a Java class with two threads 2. Thread-1 generates a random number used as a timer and pushes an object onto a queue structure. Much the same as people arriving at a check-out counter at Albertsons 3. Thread-2 pops an object off the other end at random intervals based on constraints dictated by the store or queuing process in question. For example, there is more than likely a minimum time for checking out. 4. Let the Java class run for a long period of time and generate metrics based on the queue length and service times.

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-282

Priority Queue (1 of 3)
public class Priority_Queue { LinkedList staff = new LinkedList(); ListIterator iterator = staff.listIterator(); String[] names = {"Jamie", "SuzyQ", "Jamie", "Sally", "Callie", "Celest", "Malcholm", "Goofy", "Daffy", "Eric", "George", "Sharon", "Carolyn", "Jim", "Danny", "Roger", "Will", "Gina", "Kristy", "Patty", "Lindsey"}; public Priority_Queue() { int i = 1; String entry = ""; int key = 0; Random rand = new Random(); for (i = 0; i < names.length; i++) { key = rand.nextInt(9) + 1; entry = key + names[i]; addone(entry); } dump(); }
December 30, 2006 Copyright 2004-2007, Jim Adams SLIDE-283

Priority Queue (2 of 3)
private void addone(String passed_name) Object obj = null; String name = ""; int comp = 0; { iterator = staff.listIterator(); if (iterator.hasNext()) { obj = staff.getFirst(); name = (String) obj; comp = name.compareTo(passed_name); //is the existing name greater that the one being passed? //if so, add the passed name to the beginning of the list if (comp > 0) { System.out.println("Adding to First " + passed_name); staff.addFirst(passed_name); return; } else { // loop through the linked list looking for the element higher // than the one we are inserting do { obj = iterator.next(); name = (String) obj; comp = name.compareTo(passed_name); } while (iterator.hasNext() && comp <= 0); // handle special circumstance here if (comp > 0) { iterator.previous(); } System.out.println("Adding This:" + passed_name); iterator.add(passed_name); } } else { System.out.println("Adding To a Null List:" + passed_name); staff.addFirst(passed_name); } // end of outer if

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-284

Priority Queue (3 of 3)
private void dump() { iterator = staff.listIterator(); System.out.println("\n\n\nSorted List"); while (iterator.hasNext()) { System.out.println(iterator.next()); } } // end of method

Run Output
Adding To a Null List:3Jamie Adding to First 2SuzyQ Adding This:7Jamie Adding to First 2Sally Adding to First 2Callie Adding This:2Celest Adding This:9Malcholm Adding This:4Goofy Adding This:7Daffy Adding This:7Eric Adding This:5George Adding This:6Sharon Adding This:2Carolyn Adding This:7Jim Adding This:5Danny Adding This:6Roger Adding This:6Will Adding This:4Gina Adding This:6Kristy Adding This:9Patty Adding This:8Lindsey

Sorted List 2Callie 2Carolyn 2Celest 2Sally 2SuzyQ 3Jamie 4Gina 4Goofy 5Danny 5George 6Kristy 6Roger 6Sharon 6Will 7Daffy 7Eric 7Jamie 7Jim 8Lindsey 9Malcholm 9Patty

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-285

Javas PriorityQueue Class


Some methods: 1. add() 2. clear() 3. iterator() 4. peek() 5. remove() 6. size()

java.lang.Object java.util.AbstractCollection java.util.AbstractQueue java.util.concurrent.PriorityQueue

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-286

Javas PriorityQueue Class


PriorityQueue q = new PriorityQueue(2000); for (int i=0; i<10000; i++) q.add(getRandomString()); System.out.println(q.size()); String s; s = (String) q.remove(); System.out.println(s); Need this import import java.util.PriorityQueue;

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-287

Javas PriorityBlockingQueue Class


Some methods: 1. add() 2. clear() 3. contains() 4. iterator() 5. remove() 6. size() 7. take()
java.lang.Object java.util.AbstractCollection java.util.AbstractQueue java.util.concurrent.PriorityBlockingQueue

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-288

Javas Queue Class


1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14.

PriorityBlockingQueue q = new PriorityBlockingQueue(); for (int i=0; i<10000; i++) q.add(getRandomString()); // 4-byte strings System.out.println(q.size()); String s; try { s = (String) q.take(); System.out.println(s); } catch (InterruptedException ex) { ex.printStackTrace(); }

Need this import import java.util.concurrent.PriorityBlockingQueue;

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-289

Summary Stacks Queues Expressions Theory Methods The Code

1. 2. 3. 4. 5. 6.

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-290

Sorting Data Using Java


1. 2. 3. 4.

Selection Sort Exchange Sort Merge Sort Insertion Sort

Sorting and Sorting Algorithms


How we will cover the material in this chapter
1. 2. 3.

Theory Methods Java Code

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-292

Sorting
Many types of sorting algorithms Hash Insertion Bubble Sorting and Sort Systems Selection by Harold Lorin. Shell We will focus on Tournament Shaker Selection Sort Quick Sort Merge Sort Exchange Quick Sort Poly-Phase Cascade Bubble Sort Oscillating Crisscross Merge
December 30, 2006 Copyright 2004-2007, Jim Adams SLIDE-293

Getting Ready
Before we start you will need some utility routines inside a utility class
Loader A constructor or a method to declare an array of some size and load it with random data generally integers for these tests Dumper A method to display the final sorted result, or perhaps the original data. Call the dump method passing it an array object Timer A method to get the system in milliseconds so you can time the algorithms

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-294

Selection Sort
Selection Sort Algorithm
1.

2.

3.

4. 5. 6.

Starting at the 0th element, search for the smallest element in the set 0 through n. Exchange with the 0th element Starting at element-1, search for the smallest element in the range 1 through n. When found, exchange with element-1 Starting at element-2, search for the smallest in 2 through n. Exchange with the 2nd element Starting at element-3, search for the smallest in 3 through n. Exchange with the 3rd element Continue until the nth element is reached Java Methods Needed
1. 2.

Search Swap

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-295

Selection Sort
Selection Sort Discussion
Methods
1. 2.

Search for the lowest element starting from nth element Swap the lowest element with nth element

The insertion sort is considered to be an n2 algorithm

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-296

Merge Sort
Merge Sort Algorithm-1 (Sorted Data)
1. 2. 3. 4. 5. 6. 7. 8.

Arrays should be sorted prior to merge Start at the beginning of each array, n Test both arrays elements, n Take the lower of the two and move to a new array Get the next element, n+1, in both arrays Test both arrays elements, n Take the lower of the two and move to a new array Continue until there is no more data

Array1

Array2

Merge Sort Algorithm-2 (Unsorted)


1. 2. 3. 4. 5. 6. 7. 8.

Arrays need NOT be sorted prior to merge Search each array for the lowest value, n and m Test both values n and m Take the lower of the two values and move to a new array Change the lowest value in the original arrays to MAX_VALUE so as not to select again Search each array for the lowest value, n and m Test both values n and m Take the lower of the two and move to a new array

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-297

Merge Sort
Merge Sort Discussion
1. 2. 3.

4.

5.
1.

Needs a third array to hold the sorted data More complex than Selection sort in that you need to check for sorted-ness, OR The input arrays dont need to be sorted but if they arent then you need to search each input array for the smallest element for each pass Merge sort is an n(log(n)) algorithm which grows more slowly that an n2 algorithm Methods
2. 3. 4.

Array1

Array2

Search for the Lowest Element Get an Element Put Element to the new array Mark the Lowest so we dont pick again

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-298

Bubble Sort (Exchange Sort)


Bubble Sort Algorithm
1. 2. 3. 4. 5. 6. 7. 8. 9.

Compare element-0 with element-1 If element-0 is greater than element-1, then swap the two elements Continue on with element-1 and element-2 Continue on with element-2 and element-3 Elements are known as element n and element n+1 Continue until the end of the array is reached Repeat steps 1 through 6 until no swaps are made This algorithm is known as an n2 algorithm On an array of 10 it could take as many as 100 swaps

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-299

Bubble Sort (Exchange Sort)


Bubble Sort Algorithm Discussion
1. 2. 3.

4. 5.

There are ways to speed up the bubble sort Inside the inner loop, test to see if you swapped anything If no swaps were made the sort is finished. This will usually cut the sort time in half unless the data is reversed from the start Bubble sort is an n2 algorithm Methods
1. 2.

Swap Needs two loops, inner and outer

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-300

Shaker Sort
Shaker Sort Algorithm Discussion
1. 2.

3.

A Shaker Sort is bi-directional bubble sort because we work from both ends Alternate movements between 0 and n on one pass to n and 0 on the next pass. This will move an element right to the top or bottom depending on which way you are moving. It gets its name because of the way it moves about the list, back and forth like a salt shaker or the popular beverage mixer. http://users.net1plus.com/brianl/ShakerSort.htm

4.

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-301

Insertion Sort
Insertion Sort Algorithm 1. Declare a second array the same size as the original 2. Read the original array sequentially 3. Insert each element one at a time into the new array 4. Must search for the insertion point and adjust the array contents upwards each time 5. Methods 1. Search 2. Insert 3. Bump Up
December 30, 2006

First Pass
24 12 1 19 32 6 54 9 14 24 1 34 23 33 7 34 Move the 1st to the 1st 24

Copyright 2004-2007, Jim Adams

SLIDE-302

Insertion Sort

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-303

Quick Sort
Quick Sort Algorithm
1. 2. 3.

If there are one or less elements in the array to be sorted, return immediately. Pick an element in the array to serve as a "pivot" point. (Usually the left-most element in the array is used.) Split the array into two parts - one with elements larger than the pivot and the other with elements smaller than the pivot. Recursively repeat the algorithm for both halves of the original array.

4.

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-304

Quick Sort
Quick Sort Pseudocode
int function Partition (Array A, int Lb, int Ub) begin
select a pivot from A[Lb]A[Ub]; reorder A[Lb]A[Ub] such that: all values to the left of the pivot are pivot all values to the right of the pivot are pivot return pivot position;

end; procedure QuickSort (Array A, int Lb, int Ub) begin if Lb < Ub then M = Partition (A, Lb, Ub); QuickSort (A, Lb, M 1); QuickSort (A, M, Ub); end;
December 30, 2006 Copyright 2004-2007, Jim Adams SLIDE-305

Quick Sort
Quick Sort Discussion
The quick sort is an in-place, divide-and-conquer, recursive sort. The quick sort algorithm is simple in theory, but very difficult to put into code The recursive algorithm consists of four steps which closely resemble the merge sort:
1. 2. 3. 4.

If there are one or less elements in the array to be sorted, return immediately. Pick an element in the array to serve as a "pivot" point. (Usually the left-most element in the array is used.) Split the array into two parts - one with elements larger than the pivot and the other with elements smaller than the pivot. Recursively repeat the algorithm for both halves of the original array.

The efficiency of the algorithm is impacted by which element is chosen as the pivot point. The worst-case efficiency of the quick sort, O(n2), occurs when the list is sorted and the left-most element is chosen. As long as the pivot point is chosen randomly, the quick sort has an algorithmic complexity of O(n log n).

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-306

Default algorithm for the Java Sort method


import java.util.Arrays; /** This program tests the default quicksort algorithm offered by Java */ public class QuickSortTest { public static void main(String[] args) { int[] a = ArrayUtil.randomIntArray(4000, 1000); // input array ArrayUtil.print(a, 20); Arrays.sort(a); // provided by Java ArrayUtil.print(a, 20); } }

Quick Sort is the Default for Java

Generated Output
643 675 469 993 45 496 815 646 317 892 187 793 858 587 859 380 809 871 639 331 0 0 0 1 1 2 2 2 2 3 3 3 3 3 3 3 4 4 4 4
December 30, 2006 Copyright 2004-2007, Jim Adams SLIDE-307

Sort Animation Web Site Demonstration of Selection, Bubble, Insertion, Heap, Merge and Quick Sorts
http://www.ship.edu/~cawell/Sorting/selintro.htm

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-308

public class SelectionSort { public private int int[]

Selection Sort (1 of 2)
iterations; a;
View Problem 4

// Primary constructor public SelectionSort(int[] anArray) { a = anArray; iterations=0; } // Main Sort Routine // public void sort() { int i=0; for (i = 0; i<a.length-1; i++) { int minPos = getMinimumPosition(i); swap(minPos, i); iterations++; } }
December 30, 2006 Copyright 2004-2007, Jim Adams SLIDE-309

Selection Sort (2 of 2)
// Get the element with the minimum value private int getMinimumPosition(int from) { int minPos = from; for (int i = from + 1; i < a.length; i++) if (a[i] < a[minPos]) minPos = i; return minPos;

// swap the minimum with the pivot element private void swap(int i, int j) { int temp = a[i]; a[i] = a[j]; a[j] = temp; } public void display() { System.out.println ("Iterations:" + iterations); } } // end of class
December 30, 2006 Copyright 2004-2007, Jim Adams SLIDE-310

Selection Sort Tester


/** This program tests the selection sort algorithm by sorting an array that is filled with random numbers. */ public class SelectionSortTest { public static void main(String[] args) { int[] a = ArrayUtil.randomIntArray(20, 100); ArrayUtil.print(a); SelectionSorter sorter = new SelectionSorter(a); sorter.sort(); ArrayUtil.print(a); sorter.display(); } }

Generated Output
802 758 285 476 226 328 317 435 267 246 451 79 799 543 629 928 914 900 909 483 79 226 246 267 285 317 328 435 451 476 483 543 629 758 799 802 900 909 914 928 Iterations:19
December 30, 2006 Copyright 2004-2007, Jim Adams SLIDE-311

Array Utility (1 of 3)
import java.util.Random; public class ArrayUtil { private long elapsedTime=0; private long startTime=0; private long endTime=0; // // Create an array of random integers // Passed array size and max value // public int[] createArray(int length, int n) { int[] a = new int[length]; Random generator = new Random(); for (int i = 0; i < a.length; i++) a[i] = generator.nextInt(n); } return a;
December 30, 2006 Copyright 2004-2007, Jim Adams SLIDE-312

Array Utility (2 of 3)
// // Print 50 bytes of the passed integer array // public void print(int[] a) { int arrlen=0; if (a.length>50) arrlen=50; else arrlen=a.length; for (int i = 0; i < arrlen; i++) System.out.print(a[i] + " "); } System.out.println();
December 30, 2006 Copyright 2004-2007, Jim Adams SLIDE-313

Array Utility (3 of 3)
// // Start the internal timer // public void startTimer() { startTime=System.currentTimeMillis(); } // // Stop the internal timer // public void stopTimer() { endTime=System.currentTimeMillis(); } // // Get the elapsed time // public long getElapsedTime() { elapsedTime=endTime-startTime; return(elapsedTime); } } // end of class
December 30, 2006 Copyright 2004-2007, Jim Adams SLIDE-314

Bubble Sort Example (2 of 2)


private void swap(int i) { int temp; temp = a[i]; a[i] = a[i+1]; a[i+1] = temp; } public void display() { System.out.println ("Iterations:" + iterations); }

The bubble sort is an n2 algorithm Array of 20, worst case is 400 iterations (20x20) Generated output:
814 763 628 550 564 862 104 245 579 713 11 460 321 113 647 74 389 607 65 602 11 65 74 104 113 245 321 389 460 550 564 579 602 607 628 647 713 763 814 862

Iterations:124
December 30, 2006 Copyright 2004-2007, Jim Adams SLIDE-315

Discussion Points
Sorting
1. What if there is negative numeric data in the sort sequence? 2. In a merge sort what happens if one array is exhausted first? 3. What about other data types? (Strings, Objects) 4. What about mixed data types 5. What about sorting a data file with millions of records? 6. Where do you keep the temporary data? Swap files? 7. What about sorting many data files with millions of records? 8. What about sorting various pieces of data within a record, say, name and SSN inside a record of dozens of other fields? 9. SORT3 sort utility @SORT filein,filein,filein,filein,etc KEY,1,23,9,A KEY,2,1,6,D DATA,17,6,COPY OPTIONS,MULTIKEY END
December 30, 2006 Copyright 2004-2007, Jim Adams SLIDE-316

Summary
Sorting

References for this Section Malik, D. and Nair, S. (2003). Data Structures using Java. Thomson Press. Main, Michael. (2003). Data Structures and Other Objects using Java. AddisonWesley. Horstmann, Cay. (2006). Big Java. 2nd Edition. John Wiley & Sons. Goodrich, Michael T. and Tamassia, Roberto. (2004). Data Structures and Algorithms in Java. John Wiley & Sons.

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-317

Searching Data Using Java


1. 2. 3.

Binary Search Open-address Hashing Chaining

Searching Algorithms
How we will cover the material in this chapter
1. 2. 3.

Theory Methods Java Code

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-319

Searching an Array Picture a phonebook How would you find a number by name? How would you find a name by using a number? Linear Search
Search linearly Start at the beginning and test every occurrence Sort the data Successive slicing in half
December 30, 2006 Copyright 2004-2007, Jim Adams SLIDE-320

Search alphabetically

Binary Search

Searching an Array of Integers If an array is not sorted, there is no better algorithm than a linear search for finding an element in it
public int linearSearch(int target, int[] a) { for (int i = 0; i < a.length; i++) { if (target == a[i]) return(i); } return(-1); // not a legal index }
December 30, 2006 Copyright 2004-2007, Jim Adams SLIDE-321

Searching an Array
Average Case Time
Say we have an array of 10 integers like 1,2,3,4,5,6,7,8,9,10 If we are searching for 1 then it takes one array access (hit) If we are searching for 10, then it takes 10 hits On average then, all searches take 1+2+3+4+5+6+7+8+9+10 = 5.5 10 We can generalize to
Average Case Time for Serial Search = (n + 1)/2

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-322

Searching an Array
Worst Case Time
The worst case time for a serial search is a "No Find" condition where we touch every element of the array

Best Case Time


The best case time for a serial search a hit on the very first access

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-323

Binary Search
Say we have 100 million phone numbers Sort the numbers If we are looking for 555-480-9400 To see how many tests we need we need to use logarithms
Searches = log2x, where x is the total number of items Searches = log2100000000 for example How to solve: Searches = Log10100000000 / Log102 Searches = 8 / 0.301029996 Searches = 26.57 or rounded up to 27
From Log conversion formula (Applied Mathematics, p 1.6)

logb(x) = loga(x)/loga(b)
December 30, 2006 Copyright 2004-2007, Jim Adams SLIDE-324

Binary Search
1. 2. 3.

First, sort the data (This could take some time) Say, we are searching for the number 401 Successively cut the array of data in half
Num(0) Num(1) Num(2) Num(3) Num(4) Num(5) Num(6) Num(7) Num(8) Num(9) Num(10) Num(11) Num(12) Num(13) Num(14) Num(15) Num(16) Num(17) 204 222 303 313 333 367 401 421 444 490 491 502 554 578 590 600 603 627

Middle Position

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-325

Binary Search
1.
2.

Test the middle element with the search value


If (401 > 490)
Num(0) Num(1) Num(2) Num(3) Num(4) Num(5) Num(6) Num(7) Num(8) Num(9) Num(10) Num(11) Num(12) Num(13) Num(14) Num(15) Num(16) Num(17)
December 30, 2006

3.

If true, then discard the lower half, else discard the upper half
204 222 303 313 333 367 401 421 444 490 491 502 554 578 590 600 603 627

Middle Position

Copyright 2004-2007, Jim Adams

SLIDE-326

Binary Search
1. 2. 3. 4. 5. 6. 7. 8.

Test the middle element with the search value If (401 > 333) If true, then discard the lower half, else discard the upper half Find the middle position, again Test the middle element with the search value If (401 > 303) If true, then discard the lower half, else discard the upper half You keep slicing in half until you get to the element being sought

Num(0) Num(1) Num(2) Num(3) Num(4) Num(5) Num(6) Num(7) Num(8)

204 222 303 313 333 367 401 421 444

Middle Position

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-327

Binary Search
The method call for the binary search looks like this search(a, s, n, t); a is the array to search s is the starting element n is the number of elements to search t is the target The first time you call search use 0 for the start and the array length as the length If the target is found the method returns the index otherwise it returns -1 indicating a no find condition search(int[] int first, int size, int target)

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-328

Binary Search
Code Design
if (size <=0) return (-1) else { middle = index of the midpoint of the array segment if (target == a[middle]) the target value has been found at the midpoint else if (target < a[middle]) search for the target before the midpoint else if (target > a[middle]) search for the target after the midpoint }

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-329

Binary Search
Worst Case for Binary Search O(log n) Average Time is also O(log n) Generally a recursive method

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-330

Binary Search Example (1 of 2)


public class BinarySearchTest { public static void main( String args[] ) { int location=0; ArrayUtil util = new ArrayUtil(); //create an array of 1000 elements with values less than 1000 int[] a = util.createArray(1000, 1000); SelectionSort sorter = new SelectionSort(a); BinarySearch binary = new BinarySearch(a); sorter.sort(); // array, lower, upper, item location=binary.search(a, 0, 1000, 100); System.out.println(location); // end main method // end class

} }

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-331

Binary Search Example (2 of 2)


public class BinarySearch { private int[] a;

// // Main Logic for Binary Search // public int search(int[] a, int left, int right, int target) { while (left < right) { int middle = (left + right) / 2; if (a[middle] == target) return middle ; // found else if (a[middle] > target) right = middle - 1; else left = middle + 1; } return -1; // returning -1 means "not found" } } // end of class
December 30, 2006 Copyright 2004-2007, Jim Adams SLIDE-332

Binary Search Test Results


Test Results Loaded an array of random numbers
Elements 10 100 1000 10000 100000 Test-1 3 6 9 8 8 Test-2 3 6 8 10 9 Test-3 3 6 9 6 9 Test-4 3 6 9 10 10

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-333

Open-Address Hashing
Say, we sell tractors that have stock numbers ranging 0 to 49 We could easily have an array of 50 objects to hold each tractor object Tractor[ ] data = new Tractor[50]; But what if the stock numbers are not ranged from 0 through 49. Maybe they are 0, 100, 200, 300, 400, etc What if they are W129, T900, A123, etc

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-334

Open-Address Hashing
With keys like W129, T900, A123, etc We can compute a hash code Java has a built-in hash function or we could write our own hash function If the key is numeric, we can generally use modulo division to get a key Modulo division returns a remainder from 0 to n-1 of the number being divided Example rem = x % n gives us a number between 0 and n-1
0 = 800 % 10 1 = 601 % 10

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-335

Open-Address Hashing Taking an integer modulo with a prime number


Prime number has only 1 and itself as factors This avoids patterns of addresses Easiest to analyze and most common

Folding (integer or bits)


Divide value into subgroups (k bits or digits) Add or XOR together subgroups

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-336

Open-Address Hashing
Collisions Many times an object will hash to the same address This is called collision How do we handle collisions?

Two approaches:
Open-addressing Chaining

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-337

Open-Address Hashing
Simplest open address approach is linear probing If (index == hash(key)) is not empty, try index+1, then index+2, , until empty slot Note: searching for first open address leads to primary clusters collisions bunch up Quadratic probing vary probe, like 1, 3, 6, Leads to secondary clusters but not as quickly Or completely different approach chaining

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-338

Open-Address Hashing
Store all elements in table If a cell is occupied, try another cell. Linear probing, try cells
k A B C D E F G H I J K 53 41 91 75 13 6 43 67 88 36 40 H(k) 53 mod 17 = 2 2 7 6 7 13 6 7 16 3 2 6
41 mod 17 = 7

0 1 2 3 4 5 6 7 8 9

H(k) = k mod 17

10 11 12 13 14 15 16

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-339

Open-Address Hashing
Lookup (K) { p = HashKey(K); loop { if (A[p] is empty) return false; if (A[p] == K) return true; p = (p + 1) mod m; } }
December 30, 2006 Copyright 2004-2007, Jim Adams SLIDE-340

Chaining
We could use sets or array lists or linked lists attached to each hash address Constructor allocates memory for Array List, and creates an empty list for each element of the array
put method uses hash(key) and appends to end of list at that index of array Still should resize when load factor approaches 80%

Clustering is not a problem, but long lists slow performance


remove method is easier now just delete from list

But lots more overhead than open addressing


Must store node links as well as key and info Use list method calls instead of direct array access

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-341

Chaining
0: 1: null 2: 3: null 4:

Hash maps to a key value, 0,1,2, etc Collisions chain out from each key

We could use sets or array lists or linked lists attached to each hash address
December 30, 2006 Copyright 2004-2007, Jim Adams SLIDE-342

Indexed Files
1. 2. 3. 4. An Indexed File has two, or more, parts Data is kept in the Data Part in Birth Order A separate file of keys is maintained for each key field Sometimes there can be several key files Data Part

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-343

Summary
1. 2. 3. 4. Linear Search Binary Search Open Address Hashing Chaining

Topics to Research Splay Trees Double Hashing


References for this Section Malik, D. and Nair, S. (2003). Data Structures using Java. Thomson Press. Main, Michael. (2003). Data Structures and Other Objects using Java. AddisonWesley. Horstmann, Cay. (2006). Big Java. 2nd Edition. John Wiley & Sons. Goodrich, Michael T. and Tamassia, Roberto. (2004). Data Structures and Algorithms in Java. John Wiley & Sons.
December 30, 2006 Copyright 2004-2007, Jim Adams SLIDE-344

Sets, Hash Sets, Tree Sets, Maps


1. 2. 3. 4. 5. 6. 7.

Sets Hash Sets Hash Algorithms Maps Trees Tree Sets Binary Trees

Abstract Data Structures How will we cover this material


1. 2. 3. 4. 5.

Theory Java Methods and Classes Code Examples Discussion Homework

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-346

The Collection Classes


Collection Classes
AbstractCollection AbstractList AbstractSequentialList LinkedList ArrayList AbstractSet HashSet TreeSet AbstractMap HashMap TreeMap WeakHashMap
December 30, 2006 Copyright 2004-2007, Jim Adams SLIDE-347

Sets
An unordered collection of distinct elements is called a set Elements can be added, located, removed Sets do NOT have duplicates
Adding a duplicate is ignored

A set of online printers for example

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-348

Hash Sets
Hash Sets are not sorted Hashing can be used to find elements in a data structure quickly without making a linear search A hash function computes an integer value (called the hash code) from an object A good hash function minimizes collisions, identical hash codes for different objects To compute the hash code of object x: int h = x.hashcode()
December 30, 2006 Copyright 2004-2007, Jim Adams SLIDE-349

Hash Sets
Inheritance Diagram java.lang.Object java.util.AbstractCollection java.util.AbstractSet java.util.HashSet

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-350

Hash Sets
To implement
Generate hash codes for objects Make an array or other data structure Insert each object at the location of its hash code

To test if an object is contained in the set


Compute its hash code Check if the array position with that hash code is already occupied

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-351

Hash Sets
Take Account Numbers for Example. If you do a mod 10 division and capture the remainder, each Account maps to a different value less than 10. These remainder values can be sets.
87321 87327 87333 87339 87345 87351 87357 87363 87369 87375 87381 87387 87393 87399 87405 87411 87417 87423 87429 87435 87441 87447 87453 87459 87465 87471 87477 87483 87489 87495 87501 87507 87513 87519 87525 87531 87537 87543 87549 87555 87561 87567 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 1 7 3 9 5 1 7 3 9 5 1 7 3 9 5 1 7 3 9 5 1 7 3 9 5 1 7 3 9 5 1 7 3 9 5 1 7 3 9 5 1 7

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-352

Problems with Hash Sets

It is not possible to allocate an array that is large enough to hold all possible integer index positions It is possible for two different objects to have the same hash code
December 30, 2006 Copyright 2004-2007, Jim Adams SLIDE-353

Problems with Hash Sets


Pick a reasonable array size and reduce the hash codes to fall inside the array int h = x.hashCode(); if (h < 0) h = -h; h = h % size; When elements have the same hash code: 1. Use a link sequence to store multiple objects in the same array position 2. These link sequences are called buckets

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-354

Problems with Hash Sets

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-355

Hash Codes and Functions


A hash function computes an integer hash code from an object Choose a hash function so that different objects are likely to have different hash codes. A bad choice for hash function for a string is
Adding the ASCII values of the characters in the string Because permutations ("eat" and "tea") would have the same hash code

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-356

Javas Hash Code Algorithm


Hash function for a string s from standard library
final int HASH_MULTIPLIER = 31; int h = 0; for (int i = 0; i < s.length(); i++) h = HASH_MULTIPLIER * h + s.charAt(i)

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-357

Hash Code Case Study


In 1988, I worked for Sperry Corporation The mainframe computer had a database management system called DMS Used a series of Areas, Pages and Sets The Bureau of Employment Services (OBES) tracked all unemployment claims by SSN Sperry had a standard hash algorithm that mapped data to pages SSNs seems to load up some pages and others were left empty. i.e. The distribution was very poor when it came to SSN. Worked fine for names, address, etc

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-358

Hash Code Case Study


I wrote a special hash algorithm, in assembly language, at the time I unloaded (copied) from the old database 1M SSNs to use as a test harness Wrote various programs each using a different algorithm and loaded counts into arrays that represented the pages Final result: I took the last four digits and placed them in front, then reversed the entire string Calculated a hash code based on the reversed string Did some modulo math to restrict the final hash code Remapped the entire database with all pages having data They use this SSNCALC routine to this day

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-359

Set Interface Methods


boolean add(Object o) Adds the specified element to this set if it is not already present boolean addAll(Collection c) Adds all of the elements in the specified collection to this set void clear() Removes all of the elements from this set boolean contains(Object o) Returns true if this set contains the specified element. boolean containsAll(Collection c) Returns true if this set contains all of the elements of the specified collection. boolean equals(Object o) Compares the specified object with this set for equality. int hashCode() Returns the hash code value for this set. boolean isEmpty() Returns true if this set contains no elements. Iterator iterator() Returns an iterator over the elements in this set. boolean remove(Object o) Removes the specified element from this set if it is present boolean removeAll(Collection c) Removes from this set all of its elements that are contained in the collection boolean retainAll(Collection c) Retains only the elements in this set that are contained in the collection int size() Returns the number of elements in this set (its cardinality). Object[] toArray() Returns an array containing all of the elements in this set. Object[] toArray(Object[ ] a) Returns an array containing all of the elements in this set whose runtime type is that of the specified array.

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-360

Hash Set Interface Methods


Method Summary boolean add(Object o) Adds the specified element to this set if it is not already present. void clear() Removes all of the elements from this set. Object clone() Returns a shallow copy of this HashSet instance: the elements themselves are not cloned. boolean contains(Object o) Returns true if this set contains the specified element. boolean isEmpty() Returns true if this set contains no elements. Iterator iterator() Returns an iterator over the elements in this set. boolean remove(Object o) Removes the given element from this set if it is present. int size() Returns the number of elements in this set (its cardinality).
December 30, 2006 Copyright 2004-2007, Jim Adams SLIDE-361

import java.util.Iterator; import java.util.Set; import java.util.HashSet;

Hash Set Example (1 of 2)

public class HashSet_Example { public HashSet_Example() { boolean goodAdd=false; String[] arr1 = {"Jamie", "SuzyQ", "Jamie", "Sally", "Callie", "Celest", "Malcholm", "Eric", "George", "Sharon", "Carolyn", "Jim", "Danny", "Roger", "Will", "Gina", "Eric", "Kristy"}; int i = 1; Set names = new HashSet(); System.out.println("Original Length:" + arr1.length); { goodAdd = names.add(arr1[i]); if (! goodAdd) System.out.println("Whoops. Duplicate:" + arr1[i]); } display_set(names); names.remove("Eric"); names.remove("Jamie"); display_set(names);
December 30, 2006 Copyright 2004-2007, Jim Adams SLIDE-362

Hash Set Example (2 of 2)


// // // ;--------------------------------------; Display the entire set ;--------------------------------------private void display_set(Set s) { Iterator it = s.iterator(); System.out.println("Size:" + s.size()); System.out.println("\nSet Contents"); while (it.hasNext()) { System.out.println(it.next()); } } // end of method

Original Length:18 Whoops. Duplicate: Jamie Whoops. Duplicate: Eric Size:16 Set Contents Kristy Jamie Callie Celest Eric Sally Carolyn George Jim SuzyQ Malcholm Roger Gina Will Danny Sharon Size:14 Set Contents Kristy Callie Celest Sally Carolyn George Jim SuzyQ Malcholm Roger Gina Will Danny Sharon

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-363

Tree Sets
Tree Sets store data in Sorted order Tree sets are fast
Inheritance Diagram java.lang.Object java.util.AbstractCollection java.util.AbstractSet java.util.TreeSet

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-364

Tree Set Interface Methods


boolean add(Object o) Adds the specified element to this set if it is not already present. boolean addAll(Collection c) Adds all of the elements in the specified collection to this set. void clear() Removes all of the elements from this set. Object clone() Returns a shallow copy of this TreeSet instance. boolean contains(Object o) Returns true if this set contains the specified element. Object first() Returns the first (lowest) element currently in this sorted set. boolean isEmpty() Returns true if this set contains no elements. Iterator iterator() Returns an iterator over the elements in this set. Object last() Returns the last (highest) element currently in this sorted set. boolean remove(Object o) Removes the given element from this set if it is present. int size() Returns the number of elements in this set (its cardinality).
December 30, 2006 Copyright 2004-2007, Jim Adams SLIDE-365

Tree Set Example One


import java.util.Iterator; import java.util.Set; import java.util.TreeSet;

Notice Sorted public class TreeSet_Example { Output public TreeSet_Example() { boolean goodAdd = false; String[] arr1 = { "Jamie", "SuzyQ", "Jamie", "Sally", "Callie", "Celest", "Malcholm", "Eric", "George", "Sharon", "Carolyn", "Jim", "Danny", "Roger", "Will", "Gina", "Eric", "Kristy" }; int i = 1;
TreeSet names = new TreeSet(); System.out.println("Original Length:" + arr1.length); for (i = 0; i < arr1.length; i++) { goodAdd = names.add(arr1[i]); if (! goodAdd) // handles dups System.out.println("Whoops. Duplicate:" + arr1[i]); } Iterator iterator = names.iterator(); System.out.println("Current Size:" + names.size()); while (iterator.hasNext()) System.out.println(iterator.next()); } } December 30, 2006 Copyright 2004-2007, Jim Adams

Original Length:18 Whoops. Duplicate:Jamie Whoops. Duplicate:Eric Current Size:16 Callie Carolyn Celest Danny Eric George Gina Jamie Jim Kristy Malcholm Roger Sally Sharon SuzyQ Will

SLIDE-366

import java.util.*;

Tree Set Example Showing remove Method


Original Length:18 Whoops. Duplicate:Jamie Whoops. Duplicate:Eric Delete was Successful Can't Find Selected Name:Lucy Current Size:15 Callie Carolyn Celest Danny George Gina Jamie Jim Kristy Malcholm Roger Sally Sharon SuzyQ Will

public class TreeSet_Example { public TreeSet_Example() { boolean goodAdd = false; boolean status = false; String[] arr1 = {"Jamie", "SuzyQ", "Jamie", "Sally", "Callie", "Celest", "Malcholm", "Eric", "George", "Sharon", "Carolyn", "Jim", "Danny", "Roger", "Will", "Gina", "Eric", "Kristy"}; int i = 1; TreeSet names = new TreeSet(); System.out.println("Original Length:" + arr1.length); for (i = 0; i < arr1.length; i++) { goodAdd = names.add(arr1[i]); if (!goodAdd) System.out.println("Whoops. Duplicate:" + arr1[i]); } status = names.remove("Eric"); if (status) // handles no find condition System.out.println("Delete was Successful"); else System.out.println("Can't Find Selected Name:Eric"); status = names.remove("Lucy"); if (status) // handles no find condition System.out.println("Delete was Successful"); else System.out.println("Can't Find Selected Name:Lucy"); Iterator iterator = names.iterator(); System.out.println("Current Size:" + names.size()); while (iterator.hasNext()) System.out.println(iterator.next());

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-367

Maps
A map keeps associations between key and value objects Every key in a map has a unique value. A value may be associated with several keys Classes that realize the Map interface
HashMap TreeMap Inheritance Diagram for HashMap Inheritance Diagram for TreeMap java.lang.Object java.lang.Object java.util.AbstractMap java.util.AbstractMap java.util.TreeMap java.util.HashMap

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-368

Maps
A Map is a kind of generalized array Like an array, a map is defined by "get" and "put" operations. In a map, these operations are defined not for integers 0, 1, ..., N-1, but for arbitrary Objects Some languages use the term associative array instead of "map" and use the same notation for associative arrays as for regular arrays In those languages, for example, you might see the notation A["fred"] used to indicate the item associated to the string "fred" in the associative array A Java does not use array notation for maps, but the idea is that same: A map is like an array, but the indices for a map are arbitrary objects, not integers. In a map, an object that serves as an "index" is called a key The object that is associated with a key is called a value A key can have at most one associated value, but the same value can be associated to several different keys
December 30, 2006 Copyright 2004-2007, Jim Adams SLIDE-369

Maps

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-370

Hash Map Classes & Methods


Method Summary
void clear() Removes all mappings from this map. Object clone() Returns a shallow copy of this HashMap instance: the keys and values themselves are not cloned. boolean containsKey(Object key) Returns true if this map contains a mapping for the specified key. boolean containsValue(Object value) Returns true if this map maps one or more keys to the specified value. Set entrySet() Returns a collection view of the mappings contained in this map. Object get(Object key) Returns the value to which this map maps the specified key. boolean isEmpty() Returns true if this map contains no key-value mappings. Set keySet() Returns a set view of the keys contained in this map. Object put(Object key, Object value) Associates the specified value with the specified key in this map. void putAll(Map t) Copies all of the mappings from the specified map to this one. Object remove(Object key) Removes the mapping for this key from this map if present. int size() Returns the number of key-value mappings in this map. Collection values() Returns a collection view of the values contained in this map.

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-371

Hash Map Example (1 of 4)


import import import import import import import import java.util.Iterator; java.util.Set; java.util.HashSet; java.util.Map; java.util.HashMap; java.awt.Color; java.util.Collections; java.util.Random;

public class HashMap_Example { String[] names = {"Jamie", "SuzyQ", "Shannon", "Daisy", "Manny", "Sally", "Callie", "Celest", "Malcholm", "Eric", "George", "Sharon", "Carolyn", "Jim", "Danny", "Roger", "Will", "Gina", "Tommy", "Kristy"}; String[] countries = {"USA", "China", "Mexico", "USA", "China", "France", "USA", "China", "Mexico", "China", "USA", "Mexico", "China", "USA", "USA", "USA", "Usa", "China", "USA", "China"};

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-372

Hash Map Example (2 of 4)


public HashMap_Example() { int i = 0; HashMap hashmap = new HashMap(); for (i = 0; i < names.length; i++) { hashmap.put(names[i], countries[i]); } System.out.println("The size of HashMap = " + hashmap.size()); System.out.println("If hashmap empty = " + hashmap.isEmpty()); System.out.println("The elements of HashMap are");

Set set = hashmap.keySet(); Iterator iterator = set.iterator(); while (iterator.hasNext()) { Object key = iterator.next(); Object value = hashmap.get(key); System.out.println(key + " maps to " + value); }
December 30, 2006 Copyright 2004-2007, Jim Adams SLIDE-373

Hash Map Example (3 of 4)


System.out.println("Contains this \"Danny\" Key =" + hashmap.containsKey("Danny")); System.out.println("Contains this \"USA\" Key =" + hashmap.containsKey("USA")); System.out.println("Contains this \"Spain\" Value =" + hashmap.containsValue("Spain")); hashmap.remove("Sally"); System.out.println("The size of HashMap " +hashmap.size()); System.out.println("The values of HashMap are " +hashmap.values()); hashmap.clear(); System.out.println("If hashmap empty = " + hashmap.isEmpty()); } } // end of class

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-374

Hash Map Example (4 of 4)


The size of HashMap = 20 If hashmap empty = false The elements of HashMap are Kristy maps to China Jamie maps to USA Callie maps to USA Celest maps to China Tommy maps to USA Eric maps to China Shannon maps to Mexico Sally maps to France Carolyn maps to China Manny maps to China George maps to USA Jim maps to USA SuzyQ maps to China Malcholm maps to Mexico Roger maps to USA Gina maps to China Will maps to Usa Danny maps to USA Daisy maps to USA Sharon maps to Mexico Contains this "Danny" Key =true Contains this "USA" Key =false Contains this "Spain" Value =false The size of HashMap = 19 The values of HashMap are =[China, USA, USA, China, USA, China, Mexico, China, China, USA, USA, China, Mexico, USA, China, Usa, USA, USA, Mexico] If hashmap empty = true

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-375

Tree Map Method Summary


void Object boolean boolean Object Object clear() clone() Removes all mappings from this TreeMap. Returns a shallow copy of this TreeMap instance. containsKey(Object key) Returns true if this map contains a mapping for the specified key. containsValue(Object value) Returns true if this map maps one or more keys to the specified value. Returns a set view of the mappings contained in this map. Returns the first (lowest) key currently in this sorted map. Returns the value to which this map maps the specified key. firstKey() get(Object key)

Set entrySet()

SortedMap headMap(Object toKey) Returns a view of the portion of this map whose keys are strictly less than toKey. Set keySet() Object Object void Object int size() lastKey() putAll(Map map) remove(Object key) Returns a Set view of the keys contained in this map. Returns the last (highest) key currently in this sorted map. Copies all of the mappings from the specified map to this map. Removes the mapping for this key from this TreeMap if present. Returns the number of key-value mappings in this map.

put(Object key, Object value) Associates the specified value with the specified key in this map.

SortedMap subMap(Object fromKey, Object toKey) Returns a view of the map whose keys range from fromKey, inclusive, to toKey, exclusive. SortedMap tailMap(Object fromKey) Returns a view of the map whose keys are greater than or equal to fromKey. Collection values() Returns a collection view of the values contained in this map.

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-376

Tree Map Example (1 of 4)


import import import import import import import import java.util.Iterator; java.util.Set; java.util.HashSet; java.util.Map; java.util.HashMap; java.awt.Color; java.util.Collections; java.util.Random;

public class TreeMap_Example { String[] names = {"Jamie", "SuzyQ", "Shannon", "Daisy", "Manny", "Sally", "Callie", "Celest", "Malcholm", "Eric", "George", "Sharon", "Carolyn", "Jim", "Danny", "Roger", "Will", "Gina", "Tommy", "Kristy"}; String[] countries = {"USA", "China", "Mexico", "USA", "China", "France", "USA", "China", "Mexico", "China", "USA", "Mexico", "China", "USA", "USA", "USA", "Usa", "China", "USA", "China"};

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-377

Tree Map Example (2 of 4)


public TreeMap_Example() { int i = 0; TreeMap treemap = new TreeMap(); for (i = 0; i < names.length; i++) treemap.put(names[i], countries[i]); System.out.println("The size of treemap = " + treemap.size()); System.out.println("If treemap empty = " + treemap.isEmpty()); System.out.println("The elements of treemap are"); Set set = treemap.keySet(); Iterator iterator = set.iterator(); while (iterator.hasNext()) { Object key = iterator.next(); Object value = treemap.get(key); System.out.println(key + " maps to " + value); } System.out.println("Contains this \"Danny\" Key =" + treemap.containsKey("Danny")); System.out.println("Contains this \"USA\" Key =" + treemap.containsKey("USA")); System.out.println("Contains this \"Spain\" Value =" + treemap.containsValue("Spain")); treemap.remove("Sally"); System.out.println("The size of treemap = " + treemap.size()); System.out.println("The values of treemap are =" + treemap.values()); treemap.clear(); System.out.println("If treemap empty = " + treemap.isEmpty()); SLIDE-378

December 30, 2006

Copyright 2004-2007, Jim Adams

Tree Map Example (3 of 4)


System.out.println("Contains this \"Danny\" Key =" + hashmap.containsKey("Danny")); System.out.println("Contains this \"USA\" Key =" + hashmap.containsKey("USA")); System.out.println("Contains this \"Spain\" Value =" + hashmap.containsValue("Spain")); hashmap.remove("Sally"); System.out.println("The size of HashMap " +hashmap.size()); System.out.println("The values of HashMap are " +hashmap.values()); hashmap.clear(); System.out.println("If hashmap empty = " + hashmap.isEmpty()); } } // end of class

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-379

Tree Map Example (4 of 4)


The size of HashMap = 20 If hashmap empty = false The elements of HashMap are Kristy maps to China Jamie maps to USA Callie maps to USA Celest maps to China Tommy maps to USA Eric maps to China Shannon maps to Mexico Sally maps to France Carolyn maps to China Manny maps to China George maps to USA Jim maps to USA SuzyQ maps to China Malcholm maps to Mexico Roger maps to USA Gina maps to China Will maps to Usa Danny maps to USA Daisy maps to USA Sharon maps to Mexico Contains this "Danny" Key =true Contains this "USA" Key =false Contains this "Spain" Value =false The size of HashMap = 19 The values of HashMap are =[China, USA, USA, China, USA, China, Mexico, China, China, USA, USA, China, Mexico, USA, China, Usa, USA, USA, Mexico] If hashmap empty = true

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-380

Binary Search Trees


Binary search trees allow for fast insertion and removal of elements A binary tree consists of two nodes, each of which has two child nodes All nodes in a binary search tree fulfill the property that:
o o

Descendants to the left have smaller data values than the node data value Descendants to the right have larger data values than the node data value

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-381

A Binary Search Tree

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-382

Summary Hash Maps Tree Maps Hash Sets Tree Sets Hash Codes

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-383

Java Graphical User Interfaces


Chapter Goals
1. 2. 3. 4.

5.

To use inheritance to customize panels and frames To understand Java's user interface components are added to a container To understand the use of layout managers to arrange user interface components in a container To become familiar with common user interface components such as buttons, text components, combo boxes, and menus To build programs that handle events from user interface components

SWING Books
Pure JCF Swing. Sams. Dr. Satyaraj Pantham. (1999) The JFC Swing Tutorial. Sun Press. Kathy Walrath. (1999). Core Swing, Advanced Programming. Prentice Hall. Kim Topley. (2000). Java 2 Black Book (2001). Steven Holzner. Java Look and Feel Design Guide. (2001). http://java.sun.com/products/jlf/ed2/book/
Background for this section Pages 336 358 in java software solutions 4th ed or Pages 473-518 in the Big Java 1st ed.

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-385

SWING Component Hierarchy


Java.lang.Object Java.awt.Component Java.awt.Container
Javax.swing.JComponent

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-386

SWING Components
JApplet JButton JCkeckBox JColorChooser JComboBox JDesktopPane JDialog JFileChooser JPopupMenu JProgressBar JRadioButton JFrame JLabel JList JMenu JMenuBar JMenuItem JOptionPane JPanel JPasswordField JScrollBar JSlider JTable JTextArea JTextPane JTabbedPane JSplitPane JToggleButton JToolBar JToolTip JTree

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-387

SWING Example

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-388

SWING Example

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-389

SWING Example

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-390

SWING Example
The following example illustrates 1. Checkboxes, radio buttons 2. Fonts, bold, italics 3. Borders 4. Frames and Panels 5. Combo boxes 6. Frame titles 7. GridLayout and containers 8. Event notification 9. General Code Format

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-391

SWING Example (2 of 8)
/** * Main Class for Swing Tester for CSC200 and CIS263 * @author Jim Adams */ public class Tester01 extends JFrame { private JLabel sampleField; private JCheckBox italicCheckBox; private JCheckBox boldCheckBox; private JRadioButton smallButton; private JRadioButton mediumButton; private JRadioButton largeButton; private JComboBox facenameCombo; private int private int x_loc y_loc = 0; = 0;

/** * Default Constructor * @author Jim Adams * @param None * @return Nothing */ public Tester01() { x_loc = 100; y_loc = 100; }

Code tested 05/30/2005

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-392

SWING Example (3 of 8)
/** * Main Entry Point for Public * Displays the main panel * @author Jim Adams * @param None * @return Nothing */ public void displayMainPanel() { JFrame frame = new JFrame("This is Jim's Swing Tester"); JPanel controlPanel = new JPanel(); // main panel JPanel facenamePanel = createComboBox(); // combobox panel JPanel sizeGroupPanel = createCheckBoxes(); // check box panel JPanel styleGroupPanel = createRadioButtons(); // radio button panel sampleField setSampleFont(); = new JLabel("Jim's Swing Test"); // rows, cols

controlPanel.setLayout(new GridLayout(4, 1)); controlPanel.add(sampleField); controlPanel.add(facenamePanel); controlPanel.add(sizeGroupPanel); controlPanel.add(styleGroupPanel); frame.getContentPane().add(controlPanel); frame.setSize(300, 300); frame.setLocation(x_loc, y_loc); frame.setVisible(true); frame.pack(); }

Code tested 05/30/2005

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-393

SWING Example (4 of 8)
/** * Add combo box to panel * @author Jim Adams * @param None * @return JPanel */ private JPanel createComboBox() { JPanel panel = new JPanel(); facenameCombo = new JComboBox(); facenameCombo.addItem("Serif"); facenameCombo.addItem("SansSerif"); facenameCombo.addItem("Monospaced"); facenameCombo.setEditable(true); facenameCombo.addActionListener(new ChoiceListener()); panel.add(facenameCombo); return panel; }
Code tested 05/30/2005

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-394

SWING Example (5 of 8)
/** * Add check boxes buttons to panel * @author Jim Adams * @param None * @return JPanel */ private JPanel createCheckBoxes() { JPanel panel = new JPanel(); italicCheckBox = new JCheckBox("Italic"); italicCheckBox.addActionListener(new ChoiceListener()); boldCheckBox = new JCheckBox("Bold"); boldCheckBox.addActionListener(new ChoiceListener()); panel.add(italicCheckBox); panel.add(boldCheckBox); panel.setBorder(new TitledBorder(new EtchedBorder(), "Style")); return panel; }

Code tested 05/30/2005

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-395

SWING Example (6 of 8)
/** * Add radio buttons to panel * @param None * @return JPanel */ private JPanel createRadioButtons() { JPanel panel = new JPanel(); smallButton = new JRadioButton("Small"); smallButton.addActionListener(new ChoiceListener()); mediumButton = new JRadioButton("Medium"); mediumButton.addActionListener(new ChoiceListener()); largeButton = new JRadioButton("Large"); largeButton.addActionListener(new ChoiceListener()); largeButton.setSelected(true); ButtonGroup group = new ButtonGroup(); group.add(smallButton); group.add(mediumButton); group.add(largeButton);
Code tested 05/30/2005 panel.add(smallButton); panel.add(mediumButton); panel.add(largeButton); panel.setBorder(new TitledBorder(new EtchedBorder(), "Size"));

return panel;

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-396

SWING Example (7 of 8)
/** * Set Fonts, Sizes, etc * @author Jim Adams * @param None * @return Nothing */ private void setSampleFont() { String facename = (String) facenameCombo.getSelectedItem(); int style = 0; if (italicCheckBox.isSelected()) style = style + Font.ITALIC; if (boldCheckBox.isSelected()) style = style + Font.BOLD; int size = 0; final int SMALL_SIZE = 24; final int MEDIUM_SIZE = 36; final int LARGE_SIZE = 48; if (smallButton.isSelected()) size = SMALL_SIZE; else if (mediumButton.isSelected()) size = MEDIUM_SIZE; else if (largeButton.isSelected()) size = LARGE_SIZE; sampleField.setFont(new Font(facename, style, size)); sampleField.repaint(); }

Code tested 05/30/2005

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-397

SWING Example (8 of 8)
/** * Inner Class for Action Listener * @author Jim Adams * @param None * @return Nothing */ class ChoiceListener implements ActionListener { public void actionPerformed(ActionEvent event) { setSampleFont(); } } // end of inner class

// end of main class

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-398

SWING Example
What else could we have done with this class?
1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13.

Different borders Icon on top title bar Added Images Background colors Foreground colors Locked the physical size and location Watched the mouse Add tool bars Add tool tips Add menus Add other components, buttons, sliders, etc Set a different look and feel (Windows, Mac, etc) Used different layout managers .

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-399

Frames and Windows


Primary Window Secondary Window Plain Window Utility Window

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-400

Frames and Windows


Primary Windows Primary windows are provided by the operating system of the platform on which the application is running--for instance, UNIX, Microsoft Windows, OS/2, or Macintosh. Specifically, you cannot alter the appearance of the window border and title bar, including the window controls that affect the state of a window

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-401

Frames and Windows


Secondary Windows Secondary windows (dialog boxes and alert boxes) are displayed in a window supplied by the native operating system. In the JFC, the component for dialog boxes is called JDialog, and the component for alert boxes is JOptionPane. These windows appear with the borders and title bars of the platform on which they are running.

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-402

Frames and Windows


Plain Windows You can create a window that is a blank plain rectangle. The window contains no title bar or window controls, as shown in the following figure. A plain window does not provide dragging, closing, minimizing, or maximizing. You can use a plain window as the container for a splash screen.

Image courtesy Sun Microsystems


Copyright 2004-2007, Jim Adams SLIDE-403

December 30, 2006

Frames and Windows


Utility Windows
A utility window is often used to display a collection of tools, colors, or patterns.

Unlike secondary windows, which should close automatically when their associated windows are closed, utility windows should remain open when primary windows are closed. User choices made in a utility window refer to and affect the active primary window. A utility window remains on screen for an extended period of time while users go back and forth between the utility window and primary windows. In contrast, a secondary window is designed to enable users to resolve an issue in an associated primary window and is usually dismissed once users have resolved the issue.

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-404

Organizing Window Contents Panels Scroll Panes Tabbed Panes Split Panes

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-405

Organizing Window Contents


Panels In contrast to scroll panes and tabbed panes, which typically play an interactive role in an application, a panel simply groups components within a window or another panel. Layout managers enable you to position components visually within a panel.

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-406

Organizing Window Contents


Scroll Panes A scroll pane is a specialized container offering vertical or horizontal scrollbars (or both) that enable users to change the visible portion of the window contents.
You can choose whether a scroll pane always displays scrollbars or whether they appear only when needed.

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-407

Organizing Window Contents


Scrollbars
A scrollbar is a component that enables users to control what portion of a document or list is visible on screen
A list, a combo box, a text area, or an editor pane

Both horizontal and vertical scroll boxes have a minimum size of 16 x 16 pixels so that users can still manipulate them when viewing very long documents or lists. At either end of the scrollbar is a scroll arrow, which is used for controlling small movements of the data.
December 30, 2006 Copyright 2004-2007, Jim Adams SLIDE-408

Organizing Window Contents


Tabbed Panes
A tabbed pane is a container that enables users to switch between several content panes that appear to share the same space on screen. The panes are implemented as JPanel components The tabs can contain text or images or both A typical tabbed pane appears with tabs displayed at the top, but the tabs can be displayed on any of the four sides.

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-409

Organizing Window Contents


Split Panes
A split pane is a container that divides a larger pane into resizable panes. Split panes enable users to adjust the relative sizes of two adjacent panes. The Java look and feel drag texture, along with a pointer change when the pointer is over the splitter bar, indicates that users can resize split panes. To adjust the size of the split panes, users drag the splitter bar

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-410

Organizing Window Contents


Nested Split Panes
In addition to splitting panes either horizontally or vertically, you can nest one split pane inside another.

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-411

Organizing Window Contents


Backing Windows
In an multiple document interface (MDI) application, a large window, called the backing window, contains other windows. Menus and toolbars for the application are usually displayed in the backing window rather than in each internal window The JDesktopPane component is used to implement backing windows.

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-412

Layout Management
A Container arranges its components By default, JPanel places components from left to right, then starts a new row if needed Panel layout is carried out by the FlowLayout manager You can set other layout managers if you wish
1. 2. 3. 4.

Box Layout Border Layout Grid Layout GridBag Layout

panel.setLayout(new BorderLayout()); panel.setLayout(new GridLayout(4,3,5,5,)); panel.setLayout(new GridBag(6,6));

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-413

Jims Hint:

Layout Management

1. Create JFrame Object 2. Create JPanels Objects 3. Create Border Layouts Objects 4. Create Components 5. Add Components to JPanels 6. Add JPanels to JFrames 7. Show the JFrame frame.setVisible(true);
Excellent online book by Sun Microsystems http://java.sun.com/products/jlf/ed2/book/
December 30, 2006 Copyright 2004-2007, Jim Adams SLIDE-414

Various Layout Managers BorderLayout BoxLayout CardLayout FlowLayout GridBagLayout GridLayout SpringLayout

Layout Management

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-415

Layout Management

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-416

Border Layout
Border Layout places components into geographical-based positions like center, north, west, south, east

panel.add(textField, BorderLayout.SOUTH);

Content pane of frame has Border Layout by default

frame.getContentPane().add(textField,BorderLayout.SOUTH);
Border layout grows components to fit an area To avoid growth, place component into panel (with flow layout), then add panel to content pane

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-417

Card Layout
The CardLayout class lets you implement an area that contains different components at different times A CardLayout is often controlled by a combo box, with the state of the combo box determining which panel the CardLayout displays An alternative to using CardLayout is using a tabbed pane, which provides similar functionality but with a pre-defined GUI

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-418

Spring Layout
SpringLayout is a flexible layout manager It lets you specify precise relationships between the edges of components under its control. For example, you might define that the left edge of one component is a certain distance (which can be dynamically calculated) from the right edge of a second component

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-419

Grid Layout
Lays out components in rows and columns All components have the same size

Add components left to right Top row first, then second row, etc.

panel.setLayout(new GridLayout(4, 3)); panel.add(button7); panel.add(button8); panel.add(button9); panel.add(button4); panel.add(button5); panel.add(button6); panel.add(button1); panel.add(button2); panel.add(button3);

// y, x

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-420

Grid Bag Layout


Lays out components in rows and columns Allows components to have the different sizes
JPanel p0 = new JPanel(); GridBagLayout grid = new GridBagLayout(); GridBagConstraints c = new GridBagConstraints(); JButton button = new JButton(Button1); p0.setLayout(grid); c.fill = GridBagConstraints.BOTH; c.insets = new Insets(5,5,5,5); c.gridx = 1; c.gridy = 1; c.gridwidth = 1; // width in columns c.gridheight = 1; // height in rows c.weightx=1.0; c.weighty=1.0; grid.setConstraints(button, c); p0.add(button);

// border inset

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-421

Grid Bag Layout Example (1 of 4)


Lays out components in rows and columns Allows components to have the different sizes
1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16.

Container container = null; container = this.getContentPane(); GridBagLayout grid = new GridBagLayout(); container.setLayout(grid); GridBagConstraints c = new GridBagConstraints(); c.fill = GridBagConstraints.BOTH; c.insets = new Insets(5,5,5,5); // border inset c.gridx = 1; c.gridy = 1; c.gridwidth = 1; c.gridheight = 1; c.weightx=1.0; c.weighty=1.0; JButton button = new JButton(Button1); grid.setConstraints(button, c); container.add(button);

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-422

Grid Bag Layout Example (2 of 4)


import javax.swing.*; import java.awt.*; public class LayoutTest extends JApplet { Container container = null; public void init() { container = this.getContentPane(); GridBagLayout grid = new GridBagLayout(); container.setLayout(grid); GridBagConstraints c = new GridBagConstraints(); c.insets = new Insets(5,5,5,5); . . .
December 30, 2006 Copyright 2004-2007, Jim Adams SLIDE-423

Grid Bag Layout Example (3 of 4)


// make the first button c.gridx = 1; c.gridy = 1; c.gridwidth= 1; c.gridheight=1; c.weightx=1.0; c.weighty=1.0; makeButton("Button1", grid, c); make the 2nd button c.gridx = 2; c.gridy = 2; c.gridwidth= 1; c.gridheight=1; makeButton("Button2", grid, c);

//

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-424

Grid Bag Layout Example (4 of 4)


c.gridx = 3; c.gridy = 3; c.gridwidth= 1; c.gridheight=1; c.weightx=1.0; c.weighty=1.0; makeButton("Button3", grid, c); c.gridx = 4; c.gridy = 4; makeButton("Button4", grid, c); } public void makeButton(String name, GridBagLayout g, GridBagConstraints c) { JButton button = new JButton(name); g.setConstraints(button, c); container.add(button); } }
December 30, 2006 Copyright 2004-2007, Jim Adams SLIDE-425

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-426

Box Layout
The BoxLayout class puts components in a single row or column. It respects the components' requested maximum sizes and also lets you align components.

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-427

Box Layout
Rigid Area
Use this when you want a fixed-size space between two components. For example, to put 5 pixels between two components in a left-to-right box, you can use this code:

container.add(firstComponent); container.add(Box.createRigidArea(new Dimension(5,0))); container.add(secondComponent);

http://java.sun.com/docs/books/tutorial/uiswing/layout/box.html

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-428

Box Layout
Glue
Use this to specify where excess space in a layout should go. Think of it as semiwet glue stretchy and expandable, yet taking up no space unless you pull apart the components that it's sticking to. For example, by putting horizontal glue between two components in a left-to-right box, you make any extra space go between those components, instead of to the right of all the components. Here's an example of making the space in a left-to-right box go between two components, instead of to the right of the components:

container.add(firstComponent); container.add(Box.createHorizontalGlue()); container.add(secondComponent);

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-429

Combining Layout Managers

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-430

Radio Buttons
Radio buttons are mutually exclusive Button group turns one button off when the next one is turned on sButton = new JRadioButton("Small"); mButton = new JRadioButton("Medium"); lButton = new JRadioButton("Large"); ButtonGroup group = new ButtonGroup(); group.add(sbutton); group.add(mbutton); group.add(lbutton); Buttons in a group are tested together for mutuality Button group doesn't place buttons into panel--need to add them: panel.add(sButton); Inside your action listener, test if selected if (sButton.isSelected()) . . .

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-431

Radio Buttons
Radio Button Constructors
public JRadioButton(); public JRadioButton(Icon icon); public JRadioButton(Icon icon, boolean selected); public JRadioButton(String text); public JRadioButton(String text, boolean selected); public JRadioButton(String text, Icon icon, boolean selected);

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-432

Radio Buttons Listeners


JRadioButton radio1 JRadioButton radio2 = new JRadioButton(Take Midterm); = new JRadioButton(Take Final);

radio1.addActionListener(new ButtonListener1()); radio2.addActionListener(new ButtonListener2()); private class ButtonListener1 implements ActionListener { public void actionPerformed(ActionEvent e) { Java Code for Radio Button 1 } } private class ButtonListener2 implements ActionListener { public void actionPerformed(ActionEvent e) { Java Code for Radio Button 2 } Handling each }

button with a dedicated listener


SLIDE-433

December 30, 2006

Copyright 2004-2007, Jim Adams

Radio Button Listeners


JRadioButton[] radioButtons = new JRadioButton[16]; for (int k=0; k<radioButtons.length; k++) radioButtons.addActionListener(new ButtonListener());

private class ButtonListener implements ActionListener { public void actionPerformed(ActionEvent e) { String button = e.getActionCommand(); if (button.equals("Next")) { do something } Handling many buttons } with one listener }

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-434

Check Boxes
Similar to radio button, but not mutually exclusive
JCheckBox b1 = new JCheckBox("Match Case"); JCheckBox b2 = new JCheckBox("Whole Word");

Don't place into button group


Check Box Constructors
public public public public public public JCheckBox(); JCheckBox(Icon icon); JCheckBox(Icon icon, boolean checked); JCheckBox(String text); JCheckBox(String text, boolean checked); JCheckBox(String text, Icon icon, boolean checked);

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-435

Check Boxes
Whenever a check box is selected or deselected an event of type ItemEvent is fired Methods from the ItemEvent class
public Object getItem(); // retrieves the item label public ItemSelectable getItemSelectable() public int getStateChanged()

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-436

Combo Boxes
Use less space than radio buttons Users can type other values Combo between list selection and text field JComboBox faceName = new JComboBox(); faceName.addItem("Serif"); faceName.addItem("SansSerif"); faceName.addItem("Monospaced"); Get user selection sel = (String)faceName.getSelectedItem();

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-437

Java Menus
Jims Hint: 1. Declare the Menu Bars, Menus and Menu Items 2. Add menu items to the menus 3. Add menus to the menu bar 4. Add menu bar to the JFrame 5. Add action Listeners to the menu Items 6. Add Hot Keys to menu items

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-438

Menu Items
Add menu bar to frame JMenuBar bar = new JMenuBar(); frame.setJMenuBar(bar); Add menus to the menu bar JMenu fileMenu = new JMenu("File"); bar.add(fileMenu); Add menu items to the menu JMenuItem fileNew = new JMenuItem("New"); JMenuItem fileOpen = new JMenuItem(Open"); fileMenu.add(fileNew); fileMenu.add(fileOpen); Add action listener to the menu item fileNew.addActionListener(new fileNewListener()); fileOpen.addActionListener(new fileOpenListener())

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-439

Menu Components
JMenuBar JMenu JMenu JMenu JMenu JMenu JMenu JMenuItem JMenuItem JMenuItem JMenuItem JMenuItem JMenuItem JMenuItem JMenuItem MainMenu FileMenu EditMenu ViewMenu BuildMenu ToolsMenu HelpMenu MI_New MI_Close MI_Open MI_Save MI_SaveAs MI_Print MI_Exit MI_Cut = new JMenuBar(); = = = = = = new new new new new new = = = = = = = = JMenu("File"); JMenu("Edit"); JMenu("View"); JMenu("Build"); JMenu("Tools"); JMenu("Help"); new new new new new new new new JMenuItem("New"); JMenuItem("Close"); JMenuItem("Open"); JMenuItem("Save"); JMenuItem("Save As"); JMenuItem("Print"); JMenuItem("Exit"); JMenuItem("Cut");

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-440

Menu Items
FileMenu.add(MI_New); FileMenu.add(MI_Open); FileMenu.add(MI_Save); FileMenu.add(MI_SaveAs); FileMenu.add(new JSeparator()); FileMenu.add(MI_PrinterSetup); FileMenu.add(MI_Exit); EditMenu.add(MI_Cut); EditMenu.add(MI_Copy); EditMenu.add(MI_Find); EditMenu.add(MI_Replace); EditMenu.add(MI_Paste); ViewMenu.add(MI_CrossReference); ViewMenu.add(MI_FreqTable); ViewMenu.add(MI_SymbolTable); ViewMenu.add(MI_AssembledCode); BuildMenu.add(MI_Assemble); BuildMenu.add(MI_MakeEXE); BuildMenu.add(MI_MakeCOM);

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-441

Adding Menu Items


ToolsMenu.add(MI_BaseConversion); ToolsMenu.add(MI_ShowASCII); ToolsMenu.add(MI_Register); ToolsMenu.add(MI_Preferences); HelpMenu.add(MI_Contents); HelpMenu.add(MI_About); MainMenu.add(FileMenu); MainMenu.add(EditMenu); MainMenu.add(ViewMenu); MainMenu.add(BuildMenu); MainMenu.add(ToolsMenu); MainMenu.add(HelpMenu); setJMenuBar(MainMenu); // Set up ALT Key actions and Function Key Actions MI_Exit.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X, ActionEvent.ALT_MASK)); MI_Save.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, ActionEvent.ALT_MASK)); MI_Assemble.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F9, ActionEvent.ALT_MASK)); MI_Cut.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X, ActionEvent.CTRL_MASK)); MI_Copy.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C, ActionEvent.CTRL_MASK)); MI_Paste.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_V, ActionEvent.CTRL_MASK));

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-442

Setting Menu Item Font


Font menuFont = new Font(Verdana", Font.PLAIN, 9);
FileMenu.setFont(menuFont); EditMenu.setFont(menuFont); ViewMenu.setFont(menuFont); ToolsMenu.setFont(menuFont); HelpMenu.setFont(menuFont); BuildMenu.setFont(menuFont); MI_New.setFont(menuFont); MI_Save.setFont(menuFont); MI_Open.setFont(menuFont); MI_Close.setFont(menuFont); MI_SaveAs.setFont(menuFont); MI_Print.setFont(menuFont); MI_Exit.setFont(menuFont); MI_Assemble.setFont(menuFont); MI_MakeEXE.setFont(menuFont); MI_MakeCOM.setFont(menuFont); MI_Cut.setFont(menuFont); MI_Copy.setFont(menuFont); MI_Paste.setFont(menuFont); MI_Find.setFont(menuFont); MI_Replace.setFont(menuFont);

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-443

Constructing a Slider
Constructors JSlider js = new JSlider(); Has range (0,100) with initial value of 50 JSlider(int min, int max, int value); Can specify range and initial value JSlider(int orientation, int min, int max, int value); Can use JSlider.HORIZONTAL and JSlider.VERTICAL

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-444

Constructing a Slider
Can set minimum, maximum, paint the tick marks, major spacing and minor spacing of ticks.

slider.setMajorTickSpacing(int); slider.setMinorTickSpacing(int);

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-445

Listening to a Slider
Look for addxxxListener:
void addChangeListener(ChangeListener listen)

What is a change listener? It has a single method


void stateChanged(ChangeEvent e)

How can we tell new slider setting?


int getValue()

Listener method reads all slider values and updates color


December 30, 2006 Copyright 2004-2007, Jim Adams SLIDE-446

Listening to a Slider (1 of 2)
import javax.swing.*; import javax.swing.event.*; import java.awt.*; public class Slider_Demo extends JFrame { JSlider slider = new JSlider(JSlider.HORIZONTAL,0,500,250); JLabel label = new JLabel("250",JLabel.CENTER); Font font = new Font("Verdana",Font.BOLD, 14); public Slider_Demo() { // set up the JFrame, baby JFrame frame = new JFrame(); frame.setTitle("Slider Test"); frame.setSize(350,160); // x,y frame.setVisible(true); frame.setLocation(250, 200); frame.setBackground(new Color(207,207,207)); slider.addChangeListener(new SliderListener()); slider.setPaintTicks(true); slider.setMajorTickSpacing(100); slider.setMinorTickSpacing(50); slider.setLabelTable(slider.createStandardLabels(50)); slider.setPaintLabels(true);
December 30, 2006 Copyright 2004-2007, Jim Adams

Code Tested 08/25/2004

SLIDE-447

Listening to a Slider (2 of 2)
BorderLayout maingrid = new BorderLayout(2,2); JPanel panel = new JPanel(); panel.setLayout(maingrid); // border layout panel.add(slider, BorderLayout.CENTER); panel.add(label, BorderLayout.NORTH); frame.getContentPane().add(panel); frame.show(); } class SliderListener implements ChangeListener { public void stateChanged(ChangeEvent chngEvt) { String value=""; int slidervalue=0; JSlider sliderTemp = (JSlider) chngEvt.getSource(); label.setFont(font); slidervalue=sliderTemp.getValue(); value=Integer.toString(slidervalue); label.setText(value); } // end of listener } // end of inner class // end of outer class
Code Tested 08/25/2004

View Sample Code

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-448

Java Example Panels

Image courtesy Sun Microsystems


Copyright 2004-2007, Jim Adams SLIDE-449

December 30, 2006

Java Example Panels

Images courtesy Sun Microsystems

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-450

File Chooser

Java File Chooser

View Sample Code

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-451

import java.awt.*; import javax.swing.*; import java.io.*;

File Chooser
Code tested 08/25/2004

public class Chooser { public static void main(String[] args) { int selected=0; File file = null; JFileChooser chooser = new JFileChooser(); chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES); chooser.setDialogTitle("Select Destination Directory"); chooser.setApproveButtonText("Select This File"); if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) { File selectedfile = chooser.getSelectedFile(); System.out.println(selectedfile); } if (chooser.showOpenDialog(null) == JFileChooser.CANCEL_OPTION) { System.out.println("Cancel Button Detected"); } // end of main // end of class

} }

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-452

File Chooser
static static static static static java.lang.String APPROVE_LABEL int APPROVE_OPTION java.lang.String CANCEL_LABEL int CANCEL_OPTION int ERROR_OPTION
Returns Returns Returns Get the the currently displayed directory. the currently selected file filter. the current file-selection mode. File selected by the user.

getCurrentDirectory() getFileFilter() getFileSelectionMode() getSelectedFile()

chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES); chooser.setFileSelectionMode(JFileChooser.FILES_ONLY); chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-453

Color Chooser
Constructors
public JColorChooser() public JColorChooser(Color initial color);

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-454

Color Chooser Example


import java.awt.*; import javax.swing.*; import java.awt.event.*;
View Sample Code

public class ColorChooser extends JFrame { public void Choose() { Color color = JColorChooser.showDialog(ColorChooser.this, "Select a new color...", Color.white); } } public class ColorChooserTester { public ColorChooserTester() { } public static void main(String[] args) { ColorChooser cc = new ColorChooser(); cc.Choose(); }
Code tested 08/25/2004

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-455

Progress Monitor Example (1 of 2)


import java.awt.*; import java.awt.event.*; import javax.swing.*; public class ProgressTest extends Object { public static void main( String args[] ) { // Create a frame with a single button in it. // When the button is pressed, a thread is spawned // to run out sample operation. JFrame frame = new JFrame( "ProgressMonitor Test" ); JButton button = new JButton( "Start" ); frame.getContentPane().add( button, BorderLayout.CENTER ); // Create a ProgressMonitor. This will be started // when the button is pressed. int min = 0; int max = 100; String[] message = new String[2]; message[0] = "Performing Operation."; message[1] = "This may take some time..."; final ProgressMonitor monitor = new ProgressMonitor( frame, message, "Iteration",min, max );

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-456

Progress Monitor Example (2 of 2)


// This is our sample operation. // final Runnable runnable = new Runnable() { public void run() { int sleepTime = 500; for( int i = 1; i < 100; i++ ) { try { monitor.setNote( "Iteration " + i ); monitor.setProgress( i ); if( monitor.isCanceled() ) { monitor.setProgress( 100 ); break; } Thread.sleep( sleepTime ); } catch( InterruptedException dontcare ) { } } monitor.close(); } } ; button.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent event ) { // // Run the operation in its own thread. // Thread thread = new Thread( runnable ); thread.start(); } } );

frame.pack(); frame.setVisible( true ); } } // main


December 30, 2006 Copyright 2004-2007, Jim Adams SLIDE-457

Can Also Do Split Panes

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-458

Event Listeners for GUI Components (1 of 2)


JPanel p1 = new JPanel(); // main panel // // Create Button-1 Attributes and set up listener // JButton button1; button1 = new JButton("Select File", openfileIcon); button1.setMnemonic('S'); button1.setFont(new Font("Verdana", Font.PLAIN, 10)); button1.setBackground(new Color(102,153,204)); button1.addActionListener(new SelectButtonListener()); p1.add(button1);

Jims Hint:
Declare the component such as a button, combo box, etc Set the component attributes Set the property addActionListener to point to an inner class Add the inner class with an actionPerformed method Call a method from the inner class method
December 30, 2006 Copyright 2004-2007, Jim Adams SLIDE-459

Event Listeners for GUI Components (2 of 2)


/** ******************************************************* Inner Class *********************************************************** */ private static class SelectButtonListener implements ActionListener { public void actionPerformed( ActionEvent e ) { process_select_button(); // method to call } // end of method } // end of inner class

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-460

Event Listeners for GUI Components


/** ******************************************************* Inner Class *********************************************************** */ private static class GenericButtonListener implements ActionListener { public void actionPerformed( ActionEvent e ) { JButton b = (JButton) e.getSource(); String name = b.getName(); if (name.equals(Some Text) myMethod(); } // end of method } // end of inner class

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-461

Many Other Swing Elements


JApplet JButton JCkeckBox JColorChooser JComboBox JDesktopPane JDialog JFileChooser JPopupMenu JProgressBar JRadioButton JFrame JLabel JList JMenu JMenuBar JMenuItem JOptionPane JPanel JPasswordField JScrollBar JSlider JTable JTextArea JTextPane JTabbedPane JSplitPane JToggleButton JToolBar JToolTip JTree

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-462

Swing GUI Summary


Graphical User Interfaces

Summary

1. Understand how GUI components are added to a container 2. Layout managers 3. Common user interface components, buttons, combo boxes, radio dials and menus 4. Handle events from user components

December 30, 2006

Copyright 2004-2007, Jim Adams

SLIDE-463

S-ar putea să vă placă și