Top Banner
ADVANCED DATA STRUCTURES USING J AVA 4th edition – Spring 2007 Course Syllabus Course Dynamics Class Roadmap Complete Slide Presentation Instructor: Jim Adams [email protected] [email protected]
246
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: DS Presentation

ADVANCED DATA STRUCTURES USING JAVA 4th edition – Spring 2007 Course Syllabus Course Dynamics Class Roadmap Complete Slide Presentation Instructor: Jim Adams [email protected] [email protected]

Page 2: DS Presentation

Data Structures and Algorithms Using Java 12/29/06 2

Page 3: DS Presentation

Data Structures and Algorithms Using Java 12/29/06 3

ADVANCED DATA STRUCTURES USING JAVA 4th edition – Spring 2007 Course Syllabus Course Dynamics Class Roadmap Complete Slide Presentation Instructor: Jim Adams [email protected] [email protected]

Page 4: DS Presentation

Data Structures and Algorithms Using Java 12/29/06 4

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

Page 5: DS Presentation

Data Structures and Algorithms Using Java 12/29/06 5

Contents Syllabus Complete Presentation Project Requirements Document Supplemental Reading

Page 6: DS Presentation

Data Structures and Algorithms Using Java 12/29/06 6

Page 7: DS Presentation

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

Project List for Data Structures and Algorithms HW-1 Spring 2007 CSC205

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 program’s 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.

Page 8: DS Presentation

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

Project List for Data Structures and Algorithms HW-2 Spring 2007 CSC205

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() // default 10,000 elements b) ArrayUtil(int max) // passed a number of elements to load Methods c) populateStringArray(); d) populateIntegerArray(); e) getMaximumIntegerIndex() : return int f) getMaximumIntegerValue() : return int g) exists(int) : return Boolean h) exists(string) : return Boolean i) count(int) : return int count of the search value j) count(string) : return int count of the search value k) getAverage() : return double mean value of integers l) getSum() : return long m) getArray() : return a reference to the array n) setValue(int, int) : return void o) setValue(int, String) : return void p) getElapsedTime() : return the time in milliseconds

Page 9: DS Presentation

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

Project List for Data Structures and Algorithms HW-3 Spring 2007 CSC205

q) setStartTime() : Sets the starting time value r) SetEndTime() : Sets the stop time value

Technically, methods c and d, above could be accomplished in a single method. It’s your choice. Example, populateArray(String type); 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 Java’s 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.

3.) Which collection is faster?

Page 10: DS Presentation

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

Project List for Data Structures and Algorithms HW-4 Spring 2007 CSC205

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.

2) Create a stack class using Java’s 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.

3) 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.

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.

Page 11: DS Presentation

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

Project List for Data Structures and Algorithms HW-5 Spring 2007 CSC205

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

Page 12: DS Presentation

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

Project List for Data Structures and Algorithms HW-6 Spring 2007 CSC205

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 file’s 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.

Page 13: DS Presentation

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

Project List for Data Structures and Algorithms HW-7 Spring 2007 CSC205

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:

Page 14: DS Presentation

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

Project List for Data Structures and Algorithms HW-8 Spring 2007 CSC205

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.

Page 15: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 1

Data Structures and Algorithms

Chandler Gilbert Community CollegeCSC205 – Data Structures and Algorithms

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

Subject OverviewAdvanced Data Structures (CSC205) Here is what we will learn

The Phases of Software Development Software Engineering TechniquesSpecification, Design, Implementation of Java ClassesTiming and Algorithm AnalysisCollection Classes, Arrays and Arrays ListsLinked ListsStacks & QueuesAdvanced Data Structures – Tree Sets, Hash SetsRecursive ProgrammingBinary TreesSearching & SortingSoftware Reuse with Extended ClassesSwing ProgrammingJava File I/O

Page 16: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 2

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

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

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

Tour of the Book1 Important Features of Java2 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

Page 17: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 3

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

Course Road MapSat Jan 13 Classes BeginMon Jan 15 Observance of M L King BirthdayMon Feb 19 Observance of Presidents' DayFri Mar 2 Last Day for Withdrawal without Instructor's SignatureMon-Sun Mar 12-18 Spring BreakMon Apr 23 Last Day Student Initiated Withdrawal AcceptedSun May 6 Last Day of Regular ClassesMon-Thu May 7-10 **Final Exams

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

Class Structure

Discussions During Each ClassJava, Software Engineering, Computer Science, Abstract Structures

DeliverablesTwo Tests

Two Exams

15 Java Classes as Homework Projects

11 In-Class Lab Assignments

One Critical Thinking Paper

Class and Group ActivitiesSoftware Engineering Discussions

Students Demonstrating Their Work

Student Teach-back

Page 18: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 4

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

HomeworkSee separate Homework Roadmap Document in the tail section of

this manual…

Class-1 January 22 - Introduction WeekIn 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 [email protected]

Tests: None.

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

Critical Thinking Paper

Critical Thinking Paper FormatSix 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

Page 19: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 5

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

Grading

Grading100% - 90% A89% - 80% B79% - 70% C69% - 60% DBelow 60 Oops

Grading PolicyAssignments 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.

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

Grade Distribution

Activity PercentMidterm Exam 20 %Final Exam 24 %2 Tests 10 % (2 x 5% each)

Homework Projects (15 Total) 30 % (15 x 2% each)

In Class Labs (11 Total) 11 % (11 x 1% each)

Critical Thinking Paper 5 %

Total 100 %

Extra Credit Papers 5%

Page 20: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 6

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

Outcomes and Assessments Statement Regarding Outcomes and AssessmentThe 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.

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

Students With Disabilities

Statement Regarding Students with DisabilitiesStudents 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.

Page 21: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 7

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

Plagiarism

Statement Concerning PlagiarismPlagiarism 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."

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

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) 732-7231, or visit our website at: http://www.cgc.maricopa.edu/lc

Page 22: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 8

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

Student Contact Information

On the 3x5 cards, write:

1. Name2. Phone3. Email Address4. Where You Work5. Hobbies or Interests

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

Instructor Contact and Background

Instructor InformationJim Adams (480) 229-5391Email (Business): [email protected] (Home): [email protected] Page:www.softwaredynamix.com/javashop/index.php

Division Secretary: Carlene Weberg (480) 732-7043

Software and Systems Engineer since 1978Teaching 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 MajorMBA Technology ManagementMS Systems Engineering

Page 23: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 9

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

Summary

Text BookHomework & LabsAttendanceClass StructureGradingInstructor Contact InformationUpon 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? Let’s go.

Designing Java Classes

1. Program Correctness2. JavaDoc and Java Comments3. Meaningful Variable Names4. Constants5. Code Blocks and White Space6. Cohesion and Coupling7. Accessor and Mutator Methods8. Side Effects9. Static Methods and Static Fields

Page 24: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 10

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

Black Box Effect

Black Box EffectThevenin’s Theorem in Engineering

Return a ResultPass in Arguments Method

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

Good Programming Practices

CorrectnessA 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

Page 25: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 11

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

Unique & Meaningful Variable NamesUse Meaningful Names:x = y * z; // not real clear !!

distance = speed * time; // much more cleartax = cost * tax_rate;Current = Volts * Resistance;new_balance = new_purchase + old_balance;int my_result = 0;int count = 0;

Stay away from variable names like:double J23qrsnfchar abcd;

Variables (identifiers) are case sensitiveint Adder;int adder; // these are different variables

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

Java Constants

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

Page 26: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 12

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

Magic NumbersDon’t use magic numbersMagic 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 clearh = DAYS_IN_DECEMBER * h + ch;

final int SPACE = 32;final int LINEFEED = 10;final double SQUARE_ROOT_OF_TWO = 1.414213final double PI = 3.1459

Copyright 2004-2007, Jim Adams SLIDE-24December 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!!"); } }

Page 27: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 13

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

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

Designing Classes

Classes are named after objects, like nounsVehicle class car, truck, etcBank Account class savings, checking, IRA, mortgage, etcFurniture class chair, bed, table, lamp, etcPhone class cell, analog, digital, home, workPerson class man, woman, kid, boy, girl, etc

Page 28: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 14

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

Designing ClassesClasses have methods that represent action, like verbs

Vehicle classstart_vehicle()stop_vehicle()get_mileage()get_mpg()set_parking_brake()reset_odometer();get_odometer_reading();

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

Phone classInitiate_call(number);Answer_call();

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

Let’s 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 user’s choice.

What do we need?ConstructorsMethodsCode

Let’s Choose a Class Name: NumberConverter

Page 29: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 15

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

Let’s Design a Class

Let’s 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);

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

Let’s Design a ClassLet’s deal with the method designDo 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);

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

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);

Page 30: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 16

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

Let’s Design a ClassLet’s deal with the method designDo 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){...}

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

Let’s Design a Class

What else do we need?Do we need get and set methods?

public int getBase(){

}

public void setBase(int value){

}

Page 31: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 17

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

Recent “Real Life” ExampleI just recently developed an application.Salon and Spa Appointment ManagerI started out with the following classes

Stylist ClassVendor ClassClient ClassInventory ClassService Class

I did not plan well. There is a lot of common information in theStylist, Client and Vendor classes

For example, name, address, city, state, zip, phone, email, etcI could have made a Person Class and inherited much of the

common methods and data

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

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 Purse

{public Purse(){...} public void addNickels(int count){...} public void addDimes(int count){...} public void addQuarters(int count){...} public double getTotal(){...} public static final double NICKEL_VALUE =0.05; public static final double DIME_VALUE =0.1; public static final double QUARTER_VALUE =0.25; ...

}

Why? It has two concepts: purse and coin

Page 32: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 18

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

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(){...}

}

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

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

Page 33: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 19

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

Dependency Relationships

Purse Class depends on the Coin Class.

Coin does NOT depend on Purse

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

High and Low Coupling between Classes

Page 34: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 20

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

Dependency Relationships

This concept can become tricky and confusing.

Do we link (instantiate) another class to get an object or re-code 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.

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

Accessor and Mutator Methods

Accessor: does not change the state of the implicit parameter

Mutator: changes the state of the implicit parameterRule of thumb: Mutator should return voidImmutable Class: all methods of the class are accessor

methods

private int getBalance(String account) // explicit parameter

{

this.balance = 0.0; // implicit parameter

}

Page 35: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 21

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

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

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); // questionablesendUserEmail(client_name, acct); // definite side effectthis.inquiries++; // definite side effectreturn(this.balance); // okay

}

Page 36: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 22

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

Side Effectspublic 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 separatelydeposit(1234.90, "YourAccount");printBalance("YourAccount");

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

Static MethodsEvery method must be in a class All methods wrote up to now are Instance MethodsStatic Methods are sometimes called Class MethodsMath.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

Page 37: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 23

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

Static FieldsOne field per class public class BankAccount

{private double balance;private int accountNumber;private static int lastAssignedNumber;

}public BankAccount()

{lastAssignedNumber++; // increment static fieldaccountNumber = lastAssignedNumber; // set instance field

}

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

Static

Stack

Heap

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

Page 38: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 24

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

ScopeScope 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.sqrtpublic class BankAccount

{private double balance; // class scopeprivate int accountNumber;private static int lastAssignedNumber;

public BankAccount()

{long newAccountNumber=0; // local scopelastAssignedNumber++; accountNumber = lastAssignedNumber;

}} // end of class

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

Overlapping scope: local scope wins over class scope

public class Coin{

public void draw(Graphics2D g2){

String name = "SansSerif"; // local scopeg2.setFont(new Font(name, . . .)); // local nameg2.drawString(this.name, . . .); // field name

}

private String name; // class scope. . .

}

Scope

Page 39: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 25

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

In the constructorpublic class Encrypter{

private int counter=0; // class variable

public Encrypter(int counter){

this.counter = counter;}

}

Scope

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

Instantiating an Object from a Classpublic 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;}

}

Scope

Page 40: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 26

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

public class Driver {public Driver() {}

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

System.out.println(Harvest.cnt); // Get a static VariableSystem.out.println(h.getCounter()); // Get a private Var

}}

Coupling Example

Using Our Project as an example

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

public class Harvest {private int counter=80; // private instance Variable

public int count=90; // public instance Variable

public static int cnt=100; // public static Variable

public Harvest() {}

public int getCounter(){return(counter);

}}

Coupling Example

Using Our Project as an example

Page 41: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 27

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

SummaryProgram CorrectnessJavadocClass DesignJava ConstantsVariable ScopeStatic MethodsCouplingAccessor 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/agileSoftwareDevelopment.htm

Software Engineering, Sixth Edition by Roger Pressman

Software Engineering Volume 1: The Development Process. IEEE Press.

Java Inheritance

GoalsTo understand inheritance To understand software reusability

Page 42: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 28

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

InheritanceOften you will be in a situation where a class is

close to what you need.Perhaps the class you need requires some minor

alterationAdding a few methodsChanging 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)

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

Extending a ClassExtending 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.

Page 43: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 29

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

Extending a ClassWhat is inherited?

The subclass inherits all of the variables and all of the methods defined in the superclassIt's like you had completely defined the new class from scratch and reproduced all of the code already defined in the existing superclass.

Code reuseInheritance 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.

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

InheritanceLet's Look At A Bank AccountWe can have many types of accounts.

SavingsPersonal CheckingBusiness CheckingStudent LoansHome LoansCertificate of Deposit

They are different but have some similarities.Each as a balanceEach has an account holderSome have deposits and withdrawals, some have payments

Page 44: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 30

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

InheritanceLet's Look At A VehicleWe can have many types of vehicles.

CarsTrucksPick-up TrucksSUV'sGolf Carts

They are different but have some similarities.Each as an engineEach has wheelsEach has a start mechanismEach can turn left and rightSome have tail gates and others have trunksSome have 4 wheels, some have 18

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

InheritanceBank Account Class Vehicle Class

Bank AccountSuper Class

Savings AccountSub Class

Checking AccountSub Class

VehicleSuper Class

CarSub Class

TruckSub Class

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

Car and Truck Class Would Extend the Vehicle Class

Page 45: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 31

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

Vehicle Class (First Look)public class Vehicle{

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");}

}

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

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");

}}

Page 46: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 32

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

Truck Class (First Look)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");}

}

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

Inheritance

Let's look at some more techniques used by Java

superthis

Page 47: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 33

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

Vehicle Class (Second Look)public class Vehicle {

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);

}}

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

Truck Class (Second Look)public class Truck extends Vehicle{

String truckModel;

public Truck(String model){

super.vehicleModel = model; // sets model in super classthis.truckModel = model; // sets model in this class

setEngineSize(427);setTransmissionSpeeds(4);startEngine("Truck");moveForward("Truck");turnLeft("Truck");lowerTailGate();getVehicleModel();

}

private void lowerTailGate(){

System.out.println("Lowering Tail Gate");}

}

Page 48: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 34

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

Car Class (Second Look)public class Car extends Vehicle{

String carModel;

public Car(String model){

super.vehicleModel = model; // sets model in super classthis.carModel = model; // sets model in this class

setEngineSize(283);setTransmissionSpeeds(3);startEngine("Car");moveForward("Car");turnLeft("Car");getVehicleModel();

}}

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

ExamplesCan you think of any examples of

inheritance?

Construction Worker Two-Story Home Tiger Elephant Cuckoo Clock Dime Car JPanel

Page 49: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 35

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

ExamplesCan you think of any examples of

inheritance?

Construction Worker Employee PersonTwo-Story Home DwellingTiger Carnivore Animal – OrganismElephant Herbivore Animal OrganismCuckoo Clock ClockDime Coin MoneyCar VehicleJPanel JComponent

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

ExamplesSwing Components

JComponent

JLabelJTextComponent JAbstractButton

JRadioButtonJCheckBox

JPanel

JToggleButtonJTextField JButtonJTextArea

Page 50: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 36

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

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();}

}

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

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:

Page 51: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 37

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

An Interface

interface Bicycle {

void changeCadence(int newValue);

void changeGear(int newValue);

void speedUp(int increment);

void applyBrakes(int decrement);}

Creating your own interface. Notice the empty methods

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

An Interface

/** 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")) // Break{

addBreak();}

}}

Is a model or template of an object. It has predefined methods in name only. You must supply the code.

Page 52: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 38

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

An Interface

/*** 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){

}}

Is a model or template of an object

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

Why is Reuse Important?1. Labor Cost2. Time Constraints3. Complexity4. Improved Quality

Code reuse pays off for ING - The company saved about $300,000 and 1,200 man-hoursComputerWorld. 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.

Page 53: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 39

Copyright 2004-2007, Jim Adams SLIDE-77December 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)

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

Design Patterns

Design PatternsDesign 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.

Page 54: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 40

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

Summary

SummaryExtending 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.

Software Engineering1. Software Engineering Processes2. Software Development Phases3. Specification and Design Methodologies4. Software Analysis5. Software Failure6. Issues Faced Today7. UML, Preconditions, Post Conditions

Page 55: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 41

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

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"

What is Engineering?

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

"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)

What is Software Engineering?

Page 56: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 42

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

Major cost/effort is in design, not manufactureFunctionality offered by software is unboundedComplex system decomposition and interacting processesDiscontinuous behaviorChanges to specification and design have side effectsNo agreed means of assuring qualityRequirements often ill-defined and subject to change

What's So Special About Software?

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

Software FailuresPatriot 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 1996On 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) 1993Another 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.

Page 57: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 43

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

Software FailuresDenver 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 MachineBetween 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.

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

Software Engineering Code of EthicsSoftware 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. PRODUCTSoftware engineers shall ensure that their products and related modifications meet the highest professional standards possible.

4. JUDGMENTSoftware engineers shall maintain integrity and independence in their professional judgment.

5. MANAGEMENTSoftware engineering managers and leaders shall subscribe to and promote an ethical approach to the management of software development and maintenance.

6. PROFESSIONSoftware engineers shall advance the integrity and reputation of the profession consistent with the public interest.

7. COLLEAGUESSoftware engineers shall be fair to and supportive of their colleagues.

8. SELFSoftware engineers shall participate in lifelong learning regarding the practice of their profession and shall promote an ethical approach to the practice of the profession.

http://onlineethics.org/codes/softeng.html

Page 58: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 44

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

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

Six Key Programming Issues

ModularityModifiabilityEase of UseFail-safe ProgrammingStyleDebugging

Page 59: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 45

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

Six Key Programming IssuesModularityWhy is this important?

Constructing the programDebugging the programReading the programModifying the programEliminating redundant code

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

Six Key Programming IssuesModifiability

MethodsNamed constants

Ease of UsePrompt the user for input valuesEcho the input

Page 60: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 46

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

Six Key Programming IssuesFail-safe programming

Guard against errors in the input dataGuard against errors in program logic

Method should enforce their preconditions

StyleExtensive use of methodsUse private data fieldsError handlingReadabilityDocumentation

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

Page 61: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 47

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

Software Development Methodologies

Design MethodologiesEncompasses all activities from initial analysis until obsolescence

Basic Design MethodologyAnalysis and Design MethodologyWaterfall MethodologySpiral MethodologySDLCExtreme Programming Methodology (XP)Agile Development MethodologyPBR – Plan, Build, Run

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

Basic Design Methodology

1. Define objectives2. Preliminary design of classes 3. Write the code 4. Compile the code5. Run the program6. Test and debug7. Maintain and modify8. Document

Today, we tend to use an iterative approach

Page 62: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 48

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

Basic Design Methodology

Specification of the taskDesign the solutionImplementation of the solutionAnalysis of the solutionTesting and DebuggingMaintenance and evolution of the systemObsolescence

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

Waterfall Methodology (1 of 2)

AnalysisDecide what the project is suppose to do Output: requirements document

DesignPlan how to implement the system Output:

description of classes and methods diagrams showing the relationships among the classes

Page 63: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 49

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

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

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

Analysis and Design MethodologyA. 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.

Page 64: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 50

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

Systems Development Life CyclePreliminary Investigation

Systems Analysis

Systems Design

Systems Development

Implementation

Maintenance

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

The Spiral Model

Start Here

Page 65: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 51

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

Extreme Programming (XP) (1 of 2)

Development methodology that strives for simplicity by removing formal structure and focusing on best practicesRealistic planning

Customers make business decisions Programmers make technical decisions

Small releasesRelease a useful system quickly Release updates on a short cycle

Simplicity Design as simply as possible instead of preparing for future complexities

TestingProgrammers and customers write test cases Test continuously

RefactoringRestructure the system continuously to improve code and eliminate duplication

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

Extreme Programming (XP) (2 of 2)

Pair programmingTwo programmers write code on the same computer

Collective ownershipAll programmers change all code as neededProblematic in the real world….

Continuous integrationBuild 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 customerA customer is accessible to the programming team at all times

Coding standardsFollow standards that emphasize self-documenting code

Page 66: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 52

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

Agile Development Methodology

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

Many Methodologies1. Basic Design Methodology2. Analysis and Design Methodology3. Waterfall Methodology4. Spiral Methodology5. SDLC6. Extreme Programming Methodology (XP)7. Agile Development Methodology8. PBR – Plan, Build, Run9. SCRUM10. Adaptive Software Methodology11. Crystal

Software Engineering. Theory and Practice. (2006). Pfleeger and Atlee.

Page 67: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 53

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

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

Page 68: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 54

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

Unified Modeling LanguageClass 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 othersInteraction 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 actionsActivity 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 processingPhysical 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 timeDeployment 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.

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

Unified Modeling LanguageA 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

Page 69: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 55

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

Unified Modeling LanguageClass 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

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

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

Page 70: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 56

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

Unified Modeling LanguageInteraction 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

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

Unified Modeling LanguageCollaboration 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

Page 71: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 57

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

Unified Modeling LanguageState 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

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

Unified Modeling LanguageActivity 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

Page 72: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 58

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

Unified Modeling Language

There are two types of Physicaldiagrams: 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

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

The Interaction ModelComposed of four elements:

use-casessequence diagramsstate diagrams a user interface prototype

Use Case Diagram

Sequence Diagram

Page 73: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 59

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

Unified Modeling LanguageBooks

• 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, Addison-Wesley•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

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

Page 74: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 60

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

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 ?

Preconditions and Post-conditions

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

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 ARETHE REQUIREMENTS

FOR A METHOD THAT IWANT YOU TO

WRITE.

I DON'T CAREWHAT ALGORITHM THE

METHOD USES,AS LONG AS THESE

REQUIREMENTSARE MET.

Page 75: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 61

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

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.

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

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.

Page 76: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 62

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

Example

writeSqrt(-10);writeSqrt(0);writeSqrt(5.6);

Which of these method calls meet the precondition ?

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

}

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

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.

Page 77: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 63

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

Another Examplebool 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. }

What values will be returnedby these method calls ?

is_vowel( 'A' );is_vowel(' Z' );is_vowel( '?' );

true

false

Nobody knows, because theprecondition has been violated.

Copyright 2004-2007, Jim Adams SLIDE-126December 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.

Page 78: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 64

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

Summary

SummaryEngineering Methodologies

1. Software Engineering Processes2. Software Development Phases3. Specification and Design Methodologies4. Implementation of Software Applications5. Software Failure6. Code of Ethics

Algorithms1. Software Algorithms2. Time Analysis3. Software Testing4. Big O Notation5. Debugging Techniques

Page 79: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 65

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

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

Series Expansion Algorithms

1. Analyze the algorithm

2. Look for similarities in each term

3. Numerator has x1, x3, x5, x7, xn

4. The denominator is the same as the numerator exponent as a factorial

5. Each term can be solved inside a loop

6. Could make a method for the denominator and one for the numerator

Algorithms

Taylor Series

Page 80: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 66

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

Series Expansion Algorithms

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

Algorithms

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

Series Expansion Algorithms

Where would you start on the expansion above?public double e(double x)

{double result =0.0;double numerator =0.0;double denominator =0.0;

for (int n=0; n<20; n++){

numerator = Math.pow(x,n);denominator = factorial(n);result = result + (numerator / denominator);

}return(result);

}

Algorithms

Output

20.085536921517665

Page 81: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 67

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

Hundreds of Series Expansion AlgorithmsBinomialStatisticalExponentialTrigonometricDifferentialsIntegralsFourier TransformationsEncryption

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

Algorithms

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

Page 82: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 68

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

Time AnalysisMethods1. Count the number of loop iterations, swaps, etc2. Count the times each array element is accessed3. Devise a software stopwatch and count the milliseconds of

time during execution4. Sum up all the actions

Each access takes some amount of CPU cyclesSome more, some less, but they all take cyclesAssume an “if test” takes 20 cycles per use, for exampleAssume an assignment statement takes 8 CPU cycles

5. Count the number of OperatorsUses Big O Notation

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

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

Page 83: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 69

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

Time AnalysisConsider 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. else14. average=0;

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

Time AnalysisThe 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.

Page 84: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 70

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

Time Analysis

Worst Case, Best Case and Most Likely Case

t = (wc + 4*ml + bc) / 6

Example:Worst case = 40 msBest case = 10 msMost Likely = 16ms

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

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

Big O, Algorithm Analysis

Big O Notation discussion was an excerpt from Data Structures Using Javaby D.S. Malik and P. S. Nair, pages 11-15 (2003)

Also found on Wikipedia

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

Page 85: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 71

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

Big O, Algorithm Analysis

Graph of Big O Functions

0

10

20

30

40

50

60

70

80

90

100

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

n

log nnn log nn sqr

n2

n

log n

n log nt

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

Page 86: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 72

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

Software TestingSoftware Testability

OperabilityThe better it works, the more efficiently it can be tested

ObservabilityBad output is easily found. Source code is accessible

ControllabilityIdeally, tests can be specified, automated and reproduced

DecomposabilityThe software should be built from independent modules so testing can be

done independently

SimplicityThe less there is to test, the quicker we can test it

StabilitySoftware recovers quickly and easily after a failure

UnderstandabilitySource code is well commented, documented, and organized

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

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

Page 87: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 73

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

Test Harness Examplepublic 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);}

}

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

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

Page 88: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 74

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

Test Cases

· Positive test case: expect positive outcomeExample: 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 domainFrequent cause for errorsi.e. square root of 0· This is used a lot when we have arrays of data

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

Test Case Evaluation

· ManualRun the program over and over entering data

manually

· Check property of resultExample: the square root squared = original value

· Oracle = slower way of computing answerExample. square root of x = x1/2

Page 89: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 75

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

Regression Testing

Save test cases to automate future testingjava Program < test1.in > test1.outjava Program < test2.in > test2.outjava Program < test3.in > test3.outRepeat test whenever your program changesTest suite = collection of test cases Cycling = bug that is fixed but reappears in later versionsRegression testing = testing against past failures

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

Test CoverageBlack-box testing: test functionality without understanding internal structure White-box testing: take internal structure into account when designing tests

Performance testingTest 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 applicationEasy to overlook error branches during testingMake sure to execute each branch in at least one test case

Page 90: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 76

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

Program Trace

Output statements in your program for diagnostic purposesif (status == SINGLE)

{ System.out.println("status is SINGLE"); ...

}

Or

if (DEBUGGING) // DEBUGGING is a boolean variable{

System.out.println(some_variable);}

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

Program TraceStack 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

Page 91: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 77

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

Logging

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

Log a messagelogger.info("status is SINGLE");

By default, logged messages are printed. Turn them off withlogger.setLevel(Level.OFF);

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

The DebuggerDebugger = 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

Page 92: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 78

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

The Debugger Stopping at a Breakpoint

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

Inspecting Variables

Page 93: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 79

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

Debugging Techniques

Reproduce the errorSimplify the errorDivide and conquerKnow what the program should doLook at all the detailsMake sure you understand the implication of each change before you make itDon’t make arbitrary changes

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

Summary1. Design Methodologies2. Software Engineering Processes3. Software Development Phases4. Specification and Design Methodologies5. Implementation of Software Applications6. Software Failure7. Method Timing

Further ResearchUse CasesUML DiagramsExtreme ProgrammingSDLCWaterfall MethodologySpiral ModelConcurrent Development ModelAspect Oriented Software DevelopmentAgile DevelopmentNavigation AnalysisSystems Theory

References

http://www.agilemodeling.com/essays/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/csis4650/A&D/UML_tutorial/activity.htm

Page 94: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 80

Java Arrays, Array Lists and the Collection Class

1. Learn about common array algorithms2. Arrays3. Array lists4. Single and multi-dimensional arrays5. Collections Class6. Java Vectors

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

Java ArraysAn array is used to process a collection of data with the

same data type.Examples

List of test scores or temperaturesList of names or addressesList of objects

Declaring and Creating an Arrayint score[] = new int[5];

Same As:int score1;int score2; int score3; int score4; int score5;

Page 95: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 81

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

Java Arrays

Structured way to store many of similar typed variables or objectsIndex through the array starting with zeroArrays must be declared with some predetermined sizeArrays can store numbers, strings and objectsArrays can be single dimension or multi dimension

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

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 is a primitive typebyte[] arrayOfBytes; // byte[] is an array of bytebyte[][] arrayOfArrayOfBytes; // byte[][] is an array of byte[]

Point[] points; // Point[] is an array of Point objects

Page 96: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 82

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

Declaring Arrays

Declaring and Creating an Array in Javaint junk[] = new int[200];float arr1[] = new float[2000];char arr2[] = new char[40];string names[] = new 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 listArrays arr.lengthArray Lists arr.size()Strings arr.length()

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

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"};

Page 97: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 83

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

Declaring Arrays

Declaring a Java Arrayint scores[] = new int[5];

scores[5]; // index out of bounds// Java compiler will not detect// causes runtime error

index = 12;scores[index];

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

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

0th 1st 2nd 3rd 4th i variable

0 0 0 0 0 1000 0

0th 1st 2nd 3rd 4th i variable

2 4 6 8 10 1000 0Before -

After -

Page 98: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 84

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

Java Arrays

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

// Now read these array elementsSystem.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() };

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

Java Arrays

int[] perfectNumbers = {6, 28};

This is compiled into Java byte codes that are equivalent to:

int[] perfectNumbers = new int[2];perfectNumbers[0] = 6;perfectNumbers[1] = 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 toinitialize the array, and then the Java interpreter has to execute all that initialization code

Page 99: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 85

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

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). . .

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

Multi-Dimensional Arrays

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

byte arrayOfBytes[]; // Same as byte[] arrayOfBytesbyte arrayOfArrayOfBytes[][]; // Same as byte[][] arrayOfArrayOfBytesbyte[] arrayOfArrayOfBytes[]; // Yuk! Same as byte[][] arrayOfArrayOfBytes

Page 100: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 86

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

Multi-Dimensional ArraysWhen 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} };

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

Copying Arrays

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

Page 101: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 87

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

Expanding an Array

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

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

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

Page 102: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 88

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

Defining a Java Array ListAn array list is a sequence of objectsEach object in an array list has an integer position number called an indexPosition numbers range in size from 0 to size()-12 forms for adding data

ArrayList arr = new ArrayList();arr.add( “Dave” );arr.add( “Tom” );arr.add( “Steve” );

arr.add(0, “Sally” ); // or you can use an index

arr.add(1, “Danny” );

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

Array List Methodsarr.add(object);arr.add(index, object);arr.set(index, value);arr.remove(index);arr.contains(value); //returns true/falsearr.indexOf(value); //returns index or –1arr.clear(); // clear the entire arraylistarr.get();

Page 103: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 89

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

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

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

Array List Techniques Using Collectionsimport 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);

Page 104: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 90

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

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"); // specific locationarr.add(5, "Suzie"); // specific location

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")); // returns -1. No Find

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

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

Page 105: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 91

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

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]

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

Java Vector ClassVectors are expanded as an element is addedCan 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());

Enumeration enumx = v.elements();while (enumx.hasMoreElements()) {

System.out.println("enumx: " + (Integer) enumx.nextElement());}

addElement: 9addElement: 5addElement: 54addElement: 49addElement: 60addElement: 81addElement: 8addElement: 91addElement: 76addElement: 81size: 10capacity: 15enum: 9enum: 5enum: 54enum: 49enum: 60enum: 81enum: 8enum: 91enum: 76enum: 81

Page 106: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 92

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

Summary

ArraysArray ListsVector ClassCollection Class

Material extracted from:Data Structures and the Java Collections Framework, 2nd Ed. William CollinsData Structures and Other Objects, 2nd Ed. by Michael Main

Java File I/O

Chapter Goals1. Concepts of text and binary formats2. Read and write objects3. Sequential and random file access

Page 107: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 93

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

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 bytes49 50 51 52 53, in base-1031 32 33 34 35, in hex

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

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

Streams, Readers and Writers

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

To read binary files we use the FileInputStream objectFileInputStream input =

new FileInputStream(“mybinarydata.dat”);

Found in java.io package

Page 108: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 94

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

Streams, Readers and WritersRead a text file one character at a timeimport 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

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

Streams, Readers and WritersRead a binary file one byte at a timeimport 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);

}}

}}

Page 109: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 95

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

Streams, Readers and Writers

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

To write binary files we use the FileOutputStreamobject

FileOutputStream output = new FileOuputStream(“out.dat”);

Found in java.io package

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

Streams, Readers and Writers

1. Streams access sequences of bytes

2. Readers and writers access sequences of characters

3. They process individual bytes and characters only

4. 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

Page 110: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 96

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

Streams, Readers and Writers

writer.close()

Why Close a file?Input Files

Frees the file for others to useGenerally a file is opened for exclusive use unless forced to share

Output FilesWrites the last cached output to disk

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

Common Error

Using the back slash in a file name

FileInputStream in = new FileInputStream(C:\\homework\\csc205\\pg1.java”);

Page 111: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 97

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

Common Error

Negative byte values

class Tester2{

public static void main(String[] args){

int n = 233; // binary 00000000 00000000 00000000 11101001byte b = (byte) n; // binary 11101001, with sign bit set = -105if (b != n){

System.out.println("Not Equal");}System.out.println(n);System.out.println(b);

}}

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

Reading and Writing Text FilesConstruct a PrintWriter class from any writer objectFileWriter 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();

}}

Page 112: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 98

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

Reading and Writing Text FilesReading Buffered Inputimport 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();

}}

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

Object StreamsWe can also read and write entire objects

We use ObjectOutputStream and ObjectInputStreamObjects 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();

Page 113: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 99

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

Random AccessMost data in the business world is comprised of records.Records are sets of related information

1. Databases contain sets of related files2. Files contain records3. Records contain fields4. Fields contain characters (bytes)5. Bytes are made up of bits6. 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

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

Random AccessSo far we have simply used sequential accessReading bytes from start until we reach the end of a fileEach file has a “file pointer” that points to the current position in the fileUpon opening a file, the position is 0RandomAccessFile is the random access classWorks on “fixed length” recordsCan be a fixed length of one, if necessary

long n;long filelength;RandomAccessFile f = new RandomAccessFile(“bank.dat”, “rw”);f.seek(n); // moves file pointer to byte nn = f.getFilePointer(); // get current file pointer in nfilelength=f.length(); // get the file length in bytes

File Name File Mode

Page 114: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 100

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

Random Accessimport 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(); // get current file pointer in nfilelength=f.length(); // get the file length in bytes

for (n=0; n<20; n++){

f.seek(n);ch = f.readByte(); // read a byteSystem.out.println((char) ch);

}System.out.println(filelength); // display the file length

}}

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

File DialogsJFileChooser

Let’s user navigate through their directories and select a file

Relies on another class named File

File inputfile = new File(input.txt);

Key Elementsimport java.io.*;import javax.swing.JFileChooser;

JFileChooser chooser = new JFileChooser();FileReader in = null;File selectedFile = chooser.getSelectedFile(); in = new FileReader(selectedFile);

Page 115: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 101

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

File Dialogsimport 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);}

}}

} // end of class

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

Java File I/O Summary

1. Streams use sequences of bytes2. Readers and writers access characters3. Use FileReader and FileWriter to access characters4. Use FileInputStream and FileOutputStream to access

bytes5. Use JFileChooser to let the user select a file6. Random access can read and and write records7. A file pointer is a position in a random access file8. Sequential access files are process serially

Page 116: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 102

Recursion Programming

What it isHow to do itExamples

Students learn best when they practice everyday and when they teach others

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

Introductiono Recursion is a powerful programming technique that

provides elegant solutions to certain problems.o Recursion is a programming technique in which a

method calls itself either directly, or indirectly through another method.

o Where is recursion used?o File and Directory Searcheso Traveling Salesman Problemso Shortest Route Problemso Mathematical Series Types of Problemso Sorting and Searching

Page 117: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 103

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

Overviewo AT ONE TIME OR ANOTHER, you've probably been told that you can't

define something in terms of itself. o Nevertheless, if it's done right, defining something at least partially in

terms of itself can be a very powerful technique. o A recursive definition is one that uses the concept or thing that is being

defined as part of the definition. o An "ancestor" is either a parent or an ancestor of a parent. o A "sentence" can be, among other things, two sentences joined by a

conjunction such as "and." o A "directory" is a part of a disk drive that can hold files and directories. o In mathematics, a "set" is a collection of elements, which can be other

sets. o A "statement" in Java can be a while statement, which is made up of the

word "while", a boolean-valued condition, and a statement.

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

Simple Example 1public 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}

2019181716151413121110987654321

Page 118: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 104

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

Simple Example 2public 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

hello20hello19hello18hello17hello16hello15hello14hello13hello12hello11hello10hello9hello8hello7hello6hello5hello4hello3hello2hello101234567891011121314151617181920

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

A Mathematical Example -Factorials

o Mathematical formulas often are expressed recursively.

o In the following example, we will look in depth at factorials.

Page 119: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 105

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

Definition of FactorialFactorials - !

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.

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

A Closer Look

Now, let’s 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.

Page 120: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 106

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

Factorial using Recursionpublic class Recur{

public static void main(String[] args){

System.out.println(factorial(6));}

private static long factorial(long num){

if (num == 0) // base casereturn (1);

return (num * factorial(num - 1));

}}

Each recursive call to a method produces a new set of local variables and parameters

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

Base Cases

o Base cases are important. A recursive method can solve only a base case.

o 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.

Page 121: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 107

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

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 ODSNbegin 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

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

Linear Recursion

o This simple tale has amused generations of small children precisely because it is so simple but never ends. It seems somehow paradoxical.

o Generally we want the recursion to terminate on some condition. The song `Ten Green Bottles' does not go on forever:

Page 122: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 108

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

Linear RecursionTen 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.

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

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.

Page 123: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 109

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

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.

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

Binary Searchingstatic 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()

Page 124: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 110

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

Recursive Directory Searchingprivate void get_dir(String dir_in)

{try{

File directory = new File(dir_in);File[] files = directory.listFiles();

if (files == null) // base casereturn;

for (int i=0; i<files.length; i++){

if (files[i].isDirectory()){

get_dir(files[i].toString());}else{

System.out.println(files[i]);}

}}catch (Exception ex){

}} Needs: import java.io.*;

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

Pascal’s Triangle

for(int i=0; i< 10; i++)

{

for(int j=0; j <=i; j++)

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

System.out.println();

}

public static long pascal (int n, int k)

{

if (k == 0 || k == n)

return 1;

else

return pascal(n-1,k-1) + pascal(n-1,k);

}

1

1 1

1 2 1

1 3 3 1

1 4 6 4 1

1 5 10 10 5 1

1 6 15 20 15 6 1

1 7 21 35 35 21 7 1

1 8 28 56 70 56 28 8 1

1 9 36 84 126 126 84 36 9 1

Page 125: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 111

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

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));

}

}

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

Summary

o Recursion is a powerful programming technique that provides elegant solutions to certain problems.

o Recursion is a technique in which a method calls itself either directly, or indirectly through another method.

o Base cases are usually the simplest cases a recursive method can solve.

o Recursion is Difficult to Mastero Recursion yields elegant and concise codeo Yet, it is difficult to debug

Page 126: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 112

Java Linked ListsObjectives

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 topicDiscuss theoryShow Java functions that relate to the theoryLook at an example or twoDo the homework to reinforce the theory

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

The Collection ClassesCollection Classes

AbstractCollectionAbstractListAbstractSequentialListLinkedListArrayListAbstractSetHashSetTreeSetAbstractMapHashMapTreeMapWeakHashMap

Page 127: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 113

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

Linked Lists

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

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

Linked ListsSome 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

Page 128: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 114

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

A Doubly Linked List

1. Each object points to the next one

2. Each object points to the previous one, as well

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

Adding an Element to a Linked List

1. Get the address of both sides of the location you want to add

2. Allocate a new object

3. Adjust the pointers

Page 129: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 115

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

Deleting An Object from a Linked List

1. Easier than adding

2. Simply Point around the object to be deleted

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

Managing a Sorted Linked List

Page 130: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 116

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

Linked Lists in JavaTwo ways to manage linked lists in Java:

1. The "old school" wayUses the implicit reference to an object as the linkWrite all the methods to, add, delete, insert and traverse

2. Use Java's built-in methods of the LinkedList classBuilt-in, ready made methods to add, delete, and traverse a linked list

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

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);

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);}

}

public class Node{

private int value;private Node next;

public Node(int value_in, Node n){

this.value = value_in;this.next = n;

}

}

Page 131: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 117

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

Linked List Example (2 of 2)public class Node{

private int value; // value of elementprivate Node next; // reference to next node

public Node(int value_in, Node n){

this.value = value_in;this.next = n;

}

}

Generated Output9 | csc263_stuff.LinkedList_Simulator$Node@eee36c8 | csc263_stuff.LinkedList_Simulator$Node@194df867 | csc263_stuff.LinkedList_Simulator$Node@defa1a6 | csc263_stuff.LinkedList_Simulator$Node@f5da065 | csc263_stuff.LinkedList_Simulator$Node@bd01084 | csc263_stuff.LinkedList_Simulator$Node@8ed4653 | csc263_stuff.LinkedList_Simulator$Node@11a698a2 | csc263_stuff.LinkedList_Simulator$Node@107077e1 | csc263_stuff.LinkedList_Simulator$Node@7ced01900 | nullHead Value:900Head Pointer:null

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

Managing a Linked ListAdding a new node to the head of a list

head = new Node(value, head);

Removing a node to the head of a listhead = head.getLink();

Adding a new node that is not at the head of the listSelection.addNodeAfter(current_element);link = new Node(current_node, link);

Removing a new node that is not at the head of a listSelection.removeNodeAfter();link = link.link;

Page 132: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 118

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

Managing a Linked ListHow does all this work?Every time you instantiate a new object there is an implicit reference

to it

Node node = null;

node = new Node(900, null);

node = new Node(800, node);

node = new Node(700, node);

public class Node{

private int value; // value of elementprivate Node next; // reference to next node

public Node(int value_in, Node n){

this.value = value_in;this.next = n;

}}

Null900

Null900 800

Null900 800 700

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

The Java LinkedList Classjava.lang.Object

java.util.AbstractCollectionjava.util.AbstractList

java.util.AbstractSequentialListjava.util.LinkedList

ConstructorsLinkedList() Constructs a Linked ListLinkedList(Collection c) Constructs a list containing an existing collection

Page 133: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 119

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

Java's Linked List Class Java makes it extremely easy to create and manipulate linked listsMany methods for navigation of linked listsEasy access to first and last elements with methodsJava Linked List Methods

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

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

Iterator Interface

The Iterator Interface gives access to elements inside a linked list

Used for moving forward through a linked listLinkedList list = new LinkedList(); Iterator iterator = list.iterator();

The Iterator method of the LinkedList class gets an iteratorIterator methods:Object.next()Object.hasNext()Object.remove()

while (iterator.hasNext())System.out.println(iterator.next());

Page 134: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 120

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

List Iterator InterfaceThe ListIterator Interface gives backwards access to

elements inside a linked listCan 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 iteratorList Iterator methods:Object.add()Object.hasNext()Object.hasPrevious()Object.next()Object.previous()Object.remove()Object.set()

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

Conceptual View of the List Iterator

Page 135: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 121

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

List Iterator

The next method moves the iteratoriterator.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();

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

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

}

Page 136: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 122

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

List Iterator

To move the list position backwards, use:hasPrevious

previous

while (iterator.hasPrevious()){

Object obj = iterator.previous(); //do something with the object

}

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

Adding an Object to a Linked List

The add method:Adds an object after the iteratorMoves the iterator position past the new element

iterator.add("Juliet");

Page 137: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 123

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

Removing an Object from a Linked ListThe remove method:

Removes andReturns the object that was returned by the last

call to next or previousThis loop removes all objects that fulfill a certain

conditionwhile (iterator.hasNext()) {

Object obj = iterator.next(); if (obj fulfills condition) iterator.remove();

}

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

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);

Page 138: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 124

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

Adding a Link to the Head of a Linked List

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

Removing the First ElementWhen 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 methodObject.removeFirst();

Page 139: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 125

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

Removing the First Link from a Linked List

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

Linked List Example (1 of 3)import java.util.LinkedList;import java.util.ListIterator;

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 endfor (int i = 0; i < names.length; i++){

staff.addLast(names[i]);}

// add some string objects to the frontstaff.addFirst("Sharon");staff.addFirst("George");staff.addFirst("Patty");

staff.removeFirst();staff.removeLast();

printIndexes(staff);printBirthOrder(staff);printReverseOrder(staff);

}

Page 140: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 126

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

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());}

}

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

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]));}

}234567891011-1Printing in birth orderGeorgeSharonJamieSuzieCallieMalcholmDannyDanRogerEricMikeWill

Page 141: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 127

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

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:" + (String) staff.getFirst() );System.out.println(" Last Node:" + (String) staff.getLast() );

printAll(staff);}

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

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:GeorgeLast Node:WillPrinting Entire Linked List0:George1:Sharon2:Carol3:Jamie4:Adrian5:Suzie6:Lloyd7:Johhny8:Danny9:Dan10:Roger11:Eric12:Mike13:Will

Page 142: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 128

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

Summary

1. Linked Lists2. Iterators3. List Iterators

Java Stacks and Queues

1. Stacks2. QueuesObjectivesTo become familiar with the stacks and queues

Page 143: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 129

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

Abstract Data Type -- StackThe 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

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

Abstract Data Type -- StackExamples

Web browsers store recently used URL's.Each time a user visits a new site the URL is "Pushed" onto a stackAllows 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 SystemCompilers, too

Page 144: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 130

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

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

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

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

Page 145: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 131

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

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() Returns true if stack is empty

Object peek() Gets the top object, but does not remove it

Object pop() Removes the top object

Object push(Object) Adds a new object to the top of the stack

int search(Object) Gets the position of an object

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

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

Java Stack Class - Example OneSample code to use the Java Stack classLoop 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");

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"); }

}}

Stack Size is:8HarryGammaFrankEpsilonDeltaCharlieBetaAlphaWhoops. Stack is Empty, Baby

Page 146: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 132

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

Java Stack Class - Example TwoSample code to use the Java Stack classGet 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:8HarryGammaFrankEpsilonDeltaCharlieBetaAlpha

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

Java Stack Class - Example ThreeSample code to use the Java Stack classUsing 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");

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

System.out.println(s.pop()); }

}

Stack Size is:8HarryGammaFrankEpsilonDeltaCharlieBetaAlpha

Page 147: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 133

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

Java Stack Class - Example FourSample code to use the Java Stack classUsing 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");

System.out.println(s.peek()); // look at top valueint stack_size=s.size();

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

System.out.println(n++ + ":" + s.pop()); }

}

HarryStack Size is Now:8Charlie is at Location:61:Harry2:Gamma3:Frank4:Epsilon5:Delta6:Charlie7:Beta8:Alpha

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

Stack Simulation (1 of 2)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());

}

Page 148: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 134

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

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//private static String pop(){Object obj=null;String name="";

if (iterator.hasNext()){obj=staff.getFirst();name = (String) obj;staff.removeFirst();return(name);}

else//throw new NoSuchElementException();return("End of Stack");

} // end of method

PattyGeorgeSharonMikeEricRogerWillDanMalcholmCallieSuzzyJamieEnd of StackEnd of StackEnd of Stack

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

Expression ParsingOne 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 booleanbalanced = isBalanced(expression);

Each left brace, parenthesis or bracket causes a push onto a stack structure

Each right occurrence causes a pop off the stack.

Page 149: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 135

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

Expression ParsingUsing 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

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

Expression ParsingUsing 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 unbalancedIn other words we left something on the stack

Page 150: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 136

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

Expression ParsingLet's look at this fully parenthesized expression,

double x = (((6+9)/3)*(6-4));

We need to extract the leftmost of the innermost sub-expression

(((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?

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

Expression Parsing

We need two stacks to parse an expression

1. A number stack2. 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

96

+

Number Stack Op Stack

Page 151: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 137

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

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

Our expression now looks like:

((15/3)*(6-4));

15Number Stack Op Stack

15/

Number Stack Op Stack

3

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

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))

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

5Number Stack Op Stack

5*

Number Stack Op Stack

64 -

Page 152: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 138

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

Expression Parsing

We combine 6 - 4 to get 2 and push that value onto the number stack

Our expression now looks like:

(5*2)

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

2*

Number Stack Op Stack

10Number Stack Op Stack

5

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

Expression Parsing

Issues

(((6+9)/3)*(6-4)); // numbers only are easy

( ( ( 6 + 9) / 3 ) * ( 6 - 4) ); // white space(((x+y)/q)*(6-w)); // variables( ( ( x + y) / q ) * ( 6 - w) ); // variables & white space((( x + y) / q ) * (6 – pow(w))); // embedded methods

Page 153: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 139

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

A Queue

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

Abstract Data Type -- QueuesExamples

Direct applicationsWaiting lists

StoresTheater lines

Access to shared resourcesPrinter queuesMultiprogramming

Disk I/OThread Queues

Indirect applicationsAuxiliary data structure for algorithmsComponent of other data structures

Page 154: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 140

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

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 queueMain queue operations:enqueue: inserts an element at the end of the

queuedequeue: removes and returns the element a

the front of the queue

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

Abstract Data Type -- QueueItems 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.

Page 155: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 141

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

Managing a Queue (FIFO)

Always either Adding the First object or Deleting the Last Object

Like the Check-out Lines at the Home Depot

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

FIFO Queue Discussion

Java is excellent for simulation of queued processesSupermarket checkout lines

Printer queues on LAN’sThe list is almost endlessPoint to consider:1. Create a Java class with two threads2. 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 Albertson’s

3. Thread-2 pops an object off the other end at random intervals based on constraints dictated by the store or queuing process inquestion. For example, there is more than likely a minimum timefor 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.

Page 156: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 142

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

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();

}

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

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 listif (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 insertingdo{

obj = iterator.next();name = (String) obj;comp = name.compareTo(passed_name);

}while (iterator.hasNext() && comp <= 0);// handle special circumstance hereif (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}

Page 157: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 143

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

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

Adding To a Null List:3JamieAdding to First 2SuzyQAdding This:7JamieAdding to First 2SallyAdding to First 2CallieAdding This:2CelestAdding This:9MalcholmAdding This:4GoofyAdding This:7DaffyAdding This:7EricAdding This:5GeorgeAdding This:6SharonAdding This:2CarolynAdding This:7JimAdding This:5DannyAdding This:6RogerAdding This:6WillAdding This:4GinaAdding This:6KristyAdding This:9PattyAdding This:8Lindsey

Run OutputSorted List2Callie2Carolyn2Celest2Sally2SuzyQ3Jamie4Gina4Goofy5Danny5George6Kristy6Roger6Sharon6Will7Daffy7Eric7Jamie7Jim8Lindsey9Malcholm9Patty

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

Java’s PriorityQueue ClassSome 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

Page 158: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 144

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

Java’s PriorityQueue ClassPriorityQueue 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 importimport java.util.PriorityQueue;

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

Java’s PriorityBlockingQueue ClassSome 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

Page 159: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 145

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

Java’s Queue Class1. PriorityBlockingQueue q = new PriorityBlockingQueue();2. for (int i=0; i<10000; i++)3. q.add(getRandomString()); // 4-byte strings

4. System.out.println(q.size());5. String s;6. try7. {8. s = (String) q.take();9. System.out.println(s);10. }11. catch (InterruptedException ex)12. {13. ex.printStackTrace();14. }

Need this importimport java.util.concurrent.PriorityBlockingQueue;

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

Summary

1. Stacks2. Queues3. Expressions4. Theory5. Methods6. The Code

Page 160: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 146

Sorting Data Using Java

1. Selection Sort2. Exchange Sort3. Merge Sort4. Insertion Sort

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

Sorting and Sorting Algorithms

How we will cover the material in this chapter

1. Theory2. Methods3. Java Code

Page 161: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 147

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

SortingMany types of sorting algorithms

HashInsertionBubbleSelectionShellTournamentShaker Quick SortExchangePoly-PhaseCascadeOscillatingCrisscrossMerge

Sorting and Sort Systemsby Harold Lorin. We will focus on

Selection SortMerge SortQuick SortBubble Sort

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

Getting ReadyBefore 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

Page 162: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 148

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

Selection Sort

Selection Sort Algorithm

1. Starting at the 0th element, search for the smallest element in the set 0 through n. Exchange with the 0th element

2. Starting at element-1, search for the smallest element in the range 1 through n. When found, exchange with element-1

3. Starting at element-2, search for the smallest in 2 through n. Exchange with the 2nd element

4. Starting at element-3, search for the smallest in 3 through n. Exchange with the 3rd element

5. Continue until the nth element is reached6. Java Methods Needed

1. Search2. Swap

0 1 2 3 4

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

Selection SortSelection Sort DiscussionMethods

1. Search for the lowest element starting from nth element2. Swap the lowest element with nth element

The insertion sort is considered to be an n2 algorithm

Page 163: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 149

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

Merge SortMerge Sort Algorithm-1 (Sorted Data)1. Arrays should be sorted prior to merge2. Start at the beginning of each array, n3. Test both arrays elements, n4. Take the lower of the two and move to a new array5. Get the next element, n+1, in both arrays6. Test both arrays elements, n7. Take the lower of the two and move to a new array8. Continue until there is no more data

Merge Sort Algorithm-2 (Unsorted)1. Arrays need NOT be sorted prior to merge2. Search each array for the lowest value, n and m3. Test both values n and m4. Take the lower of the two values and move to a new

array5. Change the lowest value in the original arrays to

MAX_VALUE so as not to select again6. Search each array for the lowest value, n and m7. Test both values n and m8. Take the lower of the two and move to a new array

Array1 Array2

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

Merge SortMerge Sort Discussion1. Needs a third array to hold the sorted

data2. More complex than Selection sort in that

you need to check for sorted-ness, OR…3. The input arrays don’t need to be sorted

but if they aren’t then you need to search each input array for the smallest element for each pass

4. Merge sort is an n(log(n)) algorithm which grows more slowly that an n2

algorithm5. Methods

1. Search for the Lowest Element2. Get an Element3. Put Element to the new array4. Mark the Lowest so we don’t pick again

Array1 Array2

Page 164: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 150

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

Bubble Sort (Exchange Sort)Bubble Sort Algorithm1. Compare element-0 with element-12. If element-0 is greater than element-1,

then swap the two elements3. Continue on with element-1 and element-24. Continue on with element-2 and element-35. Elements are known as element n and

element n+16. Continue until the end of the array is

reached7. Repeat steps 1 through 6 until no swaps

are made8. This algorithm is known as an n2

algorithm9. On an array of 10 it could take as many as

100 swaps

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

Bubble Sort (Exchange Sort)Bubble Sort Algorithm Discussion1. There are ways to “speed up” the

bubble sort2. Inside the inner loop, test to see if

you swapped anything3. 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

4. Bubble sort is an n2 algorithm5. Methods

1. Swap2. Needs two loops, inner and outer

Page 165: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 151

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

Shaker SortShaker Sort Algorithm Discussion1. A Shaker Sort is bi-directional bubble sort because we

work from both ends

2. 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.

3. 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.

4. http://users.net1plus.com/brianl/ShakerSort.htm

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

Insertion SortInsertion 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. Methods1. Search2. Insert3. Bump Up

24

54

6

32

19

1

12

34

1

24

14

9

24

34

7

33

23

First Pass

Move the1st to the

1st

Page 166: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 152

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

Insertion Sort

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

Quick Sort

Quick Sort Algorithm

1. If there are one or less elements in the array to be sorted, return immediately.

2. Pick an element in the array to serve as a "pivot" point. (Usually the left-most element in the array is used.)

3. Split the array into two parts - one with elements larger than the pivot and the other with elements smaller than the pivot.

4. Recursively repeat the algorithm for both halves of the original array.

Page 167: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 153

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

Quick SortQuick Sort Pseudocodeint 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 ≤ pivotall values to the right of the pivot are ≥ pivotreturn pivot position;

end;

procedure QuickSort (Array A, int Lb, int Ub)begin

if Lb < Ub thenM = Partition (A, Lb, Ub);QuickSort (A, Lb, M – 1);QuickSort (A, M, Ub);

end;

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

Quick SortQuick 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. If there are one or less elements in the array to be sorted, return immediately. 2. Pick an element in the array to serve as a "pivot" point. (Usually the left-most

element in the array is used.) 3. Split the array into two parts - one with elements larger than the pivot and the other

with elements smaller than the pivot. 4. 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).

Page 168: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 154

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

Quick Sort is the Default for JavaDefault algorithm for the Java Sort methodimport 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 JavaArrayUtil.print(a, 20);

}}

Generated Output643 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

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

Sort Animation Web Site

Demonstration of Selection, Bubble, Insertion, Heap, Merge and Quick Sorts

http://www.ship.edu/~cawell/Sorting/selintro.htm

Page 169: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 155

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

Selection Sort (1 of 2)public class SelectionSort{

public int iterations;private int[] a;

// Primary constructorpublic 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++;

}}

View Problem 4

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

Selection Sort (2 of 2)// Get the element with the minimum valueprivate 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 elementprivate 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

Page 170: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 156

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

Selection Sort Tester/**

This program tests the selection sort algorithm bysorting 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 Output802 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

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

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;}

Page 171: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 157

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

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;

elsearrlen=a.length;

for (int i = 0; i < arrlen; i++)System.out.print(a[i] + " ");

System.out.println();}

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

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

Page 172: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 158

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

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 algorithmArray 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

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

Discussion Points

Sorting1. 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 types5. 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,etcKEY,1,23,9,AKEY,2,1,6,DDATA,17,6,COPYOPTIONS,MULTIKEYEND

Page 173: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 159

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

Summary

Sorting

References for this SectionMalik, D. and Nair, S. (2003). Data Structures using Java. Thomson Press.Main, Michael. (2003). Data Structures and Other Objects using Java. Addison-

Wesley.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.

Searching Data Using Java

1. Binary Search2. Open-address Hashing3. Chaining

Page 174: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 160

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

Searching Algorithms

How we will cover the material in this chapter

1. Theory2. Methods3. Java Code

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

Searching an Array

Picture a phonebook How would you find a number by name?

Search alphabeticallyHow would you find a name by using a number?

Search linearlyLinear Search

Start at the beginning and test every occurrenceBinary Search

Sort the dataSuccessive slicing in half

Page 175: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 161

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

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

}

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

Searching an ArrayAverage Case Time

Say we have an array of 10 integers like1,2,3,4,5,6,7,8,9,10If we are searching for 1 then it takes one array access (hit)If we are searching for 10, then it takes 10 hitsOn average then, all searches take

1+2+3+4+5+6+7+8+9+10 = 5.510

We can generalize to Average Case Time for Serial Search = (n + 1)/2

Page 176: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 162

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

Searching an ArrayWorst 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 TimeThe best case time for a serial search a hit on the very first access

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

Binary SearchSay we have 100 million phone numbersSort the numbersIf we are looking for 555-480-9400To see how many tests we need we need to use logarithms

Searches = log2x, where x is the total number of itemsSearches = log2100000000 for example

How to solve:Searches = Log10100000000 / Log102Searches = 8 / 0.301029996Searches = 26.57 or rounded up to 27

From Log conversion formula (Applied Mathematics, p 1.6)logb(x) = loga(x)/loga(b)

Page 177: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 163

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

Binary Search1. First, sort the data (This could take some time)2. Say, we are searching for the number 4013. Successively cut the array of data in half

Num(0) 204Num(1) 222Num(2) 303Num(3) 313Num(4) 333Num(5) 367Num(6) 401Num(7) 421Num(8) 444Num(9) 490Num(10) 491Num(11) 502Num(12) 554Num(13) 578Num(14) 590Num(15) 600Num(16) 603Num(17) 627

Middle Position

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

Binary Search1. Test the middle element with the search value2. If (401 > 490)3. If true, then discard the lower half, else discard the upper half

Num(0) 204Num(1) 222Num(2) 303Num(3) 313Num(4) 333Num(5) 367Num(6) 401Num(7) 421Num(8) 444Num(9) 490Num(10) 491Num(11) 502Num(12) 554Num(13) 578Num(14) 590Num(15) 600Num(16) 603Num(17) 627

Middle Position

Page 178: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 164

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

Binary Search1. Test the middle element with the search value2. If (401 > 333)3. If true, then discard the lower half, else discard the upper half4. Find the middle position, again5. Test the middle element with the search value6. If (401 > 303)7. If true, then discard the lower half, else discard the upper half8. You keep slicing in half until you get to the element being sought

Num(0) 204Num(1) 222Num(2) 303Num(3) 313Num(4) 333Num(5) 367Num(6) 401Num(7) 421Num(8) 444

Middle Position

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

Binary Search

The method call for the binary search looks like this

search(a, s, n, t);a is the array to searchs is the starting elementn is the number of elements to searcht 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)

Page 179: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 165

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

Binary SearchCode Design

if (size <=0)return (-1)

else{

middle = index of the midpoint of the array segmentif (target == a[middle])

the target value has been found at the midpointelse if (target < a[middle])

search for the target before the midpointelse if (target > a[middle])

search for the target after the midpoint}

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

Binary Search

Worst Case for Binary SearchO(log n)

Average Time is alsoO(log n)

Generally a recursive method

Page 180: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 166

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

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 1000int[] a = util.createArray(1000, 1000);SelectionSort sorter = new SelectionSort(a);BinarySearch binary = new BinarySearch(a);

sorter.sort();

// array, lower, upper, itemlocation=binary.search(a, 0, 1000, 100); System.out.println(location);

} // end main method} // end class

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

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 ; // foundelse if (a[middle] > target)

right = middle - 1;else

left = middle + 1;}return -1; // returning -1 means "not found"

}} // end of class

Page 181: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 167

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

Binary Search Test Results

Test ResultsLoaded an array of random numbers

Elements Test-1 Test-2 Test-3 Test-410 3 3 3 3100 6 6 6 61000 9 8 9 910000 8 10 6 10100000 8 9 9 10

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

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

Page 182: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 168

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

Open-Address Hashing

With keys like W129, T900, A123, etcWe can compute a hash codeJava has a built-in hash function or we could write our own

hash functionIf the key is numeric, we can generally use modulo division to

get a keyModulo division returns a remainder from 0 to n-1 of the

number being dividedExamplerem = x % n gives us a number between 0 and n-10 = 800 % 101 = 601 % 10

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

Open-Address Hashing

Taking an integer modulo with a prime number

Prime number has only 1 and itself as factorsThis avoids patterns of addressesEasiest to analyze and most common

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

Page 183: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 169

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

Open-Address Hashing

CollisionsMany times an object will hash to the same addressThis is called collisionHow do we handle collisions?

Two approaches:Open-addressingChaining

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

Open-Address Hashing

Simplest open address approach is linear probingIf (index == hash(key)) is not empty, try index+1,

then index+2, …, until empty slotNote: 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”

Page 184: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 170

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

Open-Address Hashing

Store all elements in tableIf a cell is occupied, try another cell.

Linear probing, try cells

640K236J388I1667H743G66F1313E775D691C741B253AH(k)k

16

15

14

1312

11

10

9

8

7

6

5

4

3

2

1

0

H(k) = k mod 17

53 mod 17 = 2

41 mod 17 = 7

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

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;}

}

Page 185: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 171

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

Chaining

We could use sets or array lists or linked lists attached to each hash addressConstructor 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 arrayStill should resize when load factor approaches 80%

Clustering is not a problem, but long lists slow performanceremove method is easier now – just delete from list

But lots more overhead than open addressingMust store node links as well as key and infoUse list method calls instead of direct array access

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

Chaining

Hash maps to a key value, 0,1,2, etc

Collisions chain out from each key null

null

4:3:2:1:0:

We could use sets or array lists or linked lists attached to each hash address

Page 186: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 172

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

Indexed Files

1. An Indexed File has two, or more, parts2. Data is kept in the Data Part in Birth Order3. A separate file of keys is maintained for each key field4. Sometimes there can be several key files

Data Part

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

Summary

1. Linear Search2. Binary Search3. Open Address Hashing4. Chaining

Topics to Research• Splay Trees• Double Hashing

References for this SectionMalik, D. and Nair, S. (2003). Data Structures using Java. Thomson Press.Main, Michael. (2003). Data Structures and Other Objects using Java. Addison-

Wesley.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.

Page 187: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 173

Sets, Hash Sets, Tree Sets, Maps

1. Sets2. Hash Sets3. Hash Algorithms4. Maps5. Trees6. Tree Sets7. Binary Trees

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

Abstract Data Structures

How will we cover this material1. Theory2. Java Methods and Classes3. Code Examples4. Discussion5. Homework

Page 188: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 174

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

The Collection Classes

Collection ClassesAbstractCollectionAbstractListAbstractSequentialListLinkedListArrayListAbstractSetHashSetTreeSetAbstractMapHashMapTreeMapWeakHashMap

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

SetsAn unordered collection of distinct elements is called a setElements can be added, located, removedSets do NOT have duplicates

Adding a duplicate is ignoredA set of online printers for example

Page 189: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 175

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

Hash Sets

Hash Sets are not sortedHashing 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()

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

Hash SetsInheritance Diagramjava.lang.Object

java.util.AbstractCollectionjava.util.AbstractSet

java.util.HashSet

Page 190: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 176

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

Hash SetsTo implement

Generate hash codes for objects Make an array or other data structureInsert 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

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

Hash SetsTake 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 10 187327 10 787333 10 387339 10 987345 10 587351 10 187357 10 787363 10 387369 10 987375 10 587381 10 187387 10 787393 10 387399 10 987405 10 587411 10 187417 10 787423 10 387429 10 987435 10 587441 10 187447 10 787453 10 387459 10 987465 10 587471 10 187477 10 787483 10 387489 10 987495 10 587501 10 187507 10 787513 10 387519 10 987525 10 587531 10 187537 10 787543 10 387549 10 987555 10 587561 10 187567 10 7

Page 191: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 177

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

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

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

Problems with Hash SetsPick 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

Page 192: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 178

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

Problems with Hash Sets

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

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 isAdding the ASCII values of the characters in the string Because permutations ("eat" and "tea") would have the same hash code

Page 193: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 179

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

Java’s 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)

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

Hash Code Case Study

In 1988, I worked for Sperry CorporationThe mainframe computer had a database management system called DMSUsed a series of Areas, Pages and SetsThe Bureau of Employment Services (OBES) tracked all unemployment claims by SSNSperry had a standard hash algorithm that mapped data to pagesSSN’s 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

Page 194: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 180

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

Hash Code Case Study

I wrote a special hash algorithm, in assembly language, at the timeI unloaded (copied) from the old database 1M SSNs to use as a test harnessWrote various programs each using a different algorithm and loaded counts into arrays that represented the pagesFinal result: I took the last four digits and placed them in front, then reversed the entire stringCalculated a hash code based on the reversed stringDid some modulo math to restrict the final hash codeRemapped the entire database with all pages having dataThey use this SSNCALC routine to this day

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

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 setvoid clear() Removes all of the elements from this set booleancontains(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 presentboolean 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.

Page 195: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 181

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

Hash Set Interface MethodsMethod 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).

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

Hash Set Example (1 of 2)import java.util.Iterator;import java.util.Set;import java.util.HashSet;

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);

}

Page 196: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 182

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

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:18Whoops. Duplicate: JamieWhoops. Duplicate: EricSize:16

Set ContentsKristyJamieCallieCelestEricSallyCarolynGeorgeJimSuzyQMalcholmRogerGinaWillDannySharonSize:14

Set ContentsKristyCallieCelestSallyCarolynGeorgeJimSuzyQMalcholmRogerGinaWillDannySharon

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

Tree Sets

Tree Sets store data in Sorted orderTree sets are fast

Inheritance Diagramjava.lang.Object

java.util.AbstractCollectionjava.util.AbstractSet

java.util.TreeSet

Page 197: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 183

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

Tree Set Interface Methodsboolean 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).

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

Tree Set Example Oneimport java.util.Iterator;import java.util.Set;import java.util.TreeSet;

public class TreeSet_Example{

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());}

}

Original Length:18Whoops. Duplicate:JamieWhoops. Duplicate:EricCurrent Size:16CallieCarolynCelestDannyEricGeorgeGinaJamieJimKristyMalcholmRogerSallySharonSuzyQWill

Notice Sorted Output

Page 198: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 184

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

Tree Set Example Showing remove Methodimport java.util.*;

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 conditionSystem.out.println("Delete was Successful");

elseSystem.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());

}}

Original Length:18Whoops. Duplicate:JamieWhoops. Duplicate:EricDelete was SuccessfulCan't Find Selected Name:LucyCurrent Size:15CallieCarolynCelestDannyGeorgeGinaJamieJimKristyMalcholmRogerSallySharonSuzyQWill

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

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 keysClasses that realize the Map interfaceHashMap

TreeMap

Inheritance Diagram for HashMapjava.lang.Object

java.util.AbstractMapjava.util.HashMap

Inheritance Diagram for TreeMapjava.lang.Object

java.util.AbstractMapjava.util.TreeMap

Page 199: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 185

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

MapsA 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 ObjectsSome languages use the term associative array instead of "map" and use the same notation for associative arrays as for regular arraysIn 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 AJava 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 keyThe object that is associated with a key is called a valueA key can have at most one associated value, but the same value can be associated to several different keys

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

Maps

Page 200: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 186

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

Hash Map Classes & MethodsMethod Summaryvoid 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.

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

Hash Map Example (1 of 4)import java.util.Iterator;import java.util.Set;import java.util.HashSet;import java.util.Map;import java.util.HashMap;import java.awt.Color;import java.util.Collections;import 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"};

Page 201: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 187

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

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);

}

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

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

Page 202: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 188

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

Hash Map Example (4 of 4)The size of HashMap = 20If hashmap empty = falseThe elements of HashMap areKristy maps to ChinaJamie maps to USACallie maps to USACelest maps to ChinaTommy maps to USAEric maps to ChinaShannon maps to MexicoSally maps to FranceCarolyn maps to ChinaManny maps to ChinaGeorge maps to USAJim maps to USASuzyQ maps to ChinaMalcholm maps to MexicoRoger maps to USAGina maps to ChinaWill maps to UsaDanny maps to USADaisy maps to USASharon maps to MexicoContains this "Danny" Key =trueContains this "USA" Key =falseContains this "Spain" Value =falseThe size of HashMap = 19The 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

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

Tree Map Method Summaryvoid clear() Removes all mappings from this TreeMap.Object clone() Returns a shallow copy of this TreeMap instance.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 set view of the mappings contained in this map.Object firstKey() Returns the first (lowest) key currently in this sorted map.Object get(Object key) Returns the value to which this map maps the specified key.SortedMap headMap(Object toKey) Returns a view of the portion of this map whose keys are strictly less than

toKey.Set keySet() Returns a Set view of the keys contained in this map.Object lastKey() Returns the last (highest) key currently in this sorted map.Object put(Object key, Object value) Associates the specified value with the specified key in this map.void putAll(Map map) Copies all of the mappings from the specified map to this map.Object remove(Object key) Removes the mapping for this key from this TreeMap if present.int size() Returns the number of key-value mappings 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.

Page 203: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 189

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

Tree Map Example (1 of 4)import java.util.Iterator;import java.util.Set;import java.util.HashSet;import java.util.Map;import java.util.HashMap;import java.awt.Color;import java.util.Collections;import 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"};

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

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());

}}

Page 204: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 190

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

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

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

Tree Map Example (4 of 4)The size of HashMap = 20If hashmap empty = falseThe elements of HashMap areKristy maps to ChinaJamie maps to USACallie maps to USACelest maps to ChinaTommy maps to USAEric maps to ChinaShannon maps to MexicoSally maps to FranceCarolyn maps to ChinaManny maps to ChinaGeorge maps to USAJim maps to USASuzyQ maps to ChinaMalcholm maps to MexicoRoger maps to USAGina maps to ChinaWill maps to UsaDanny maps to USADaisy maps to USASharon maps to MexicoContains this "Danny" Key =trueContains this "USA" Key =falseContains this "Spain" Value =falseThe size of HashMap = 19The 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

Page 205: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 191

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

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 Descendants to the left have smaller data values than the

node data value o Descendants to the right have larger data values than the

node data value

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

A Binary Search Tree

Page 206: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 192

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

Summary

Hash MapsTree MapsHash SetsTree SetsHash Codes

Java Graphical User Interfaces

Chapter Goals1. To use inheritance to customize panels and frames 2. To understand Java's user interface components are added

to a container 3. To understand the use of layout managers to arrange user

interface components in a container4. To become familiar with common user interface

components such as buttons, text components, combo boxes, and menus

5. To build programs that handle events from user interface components

Page 207: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 193

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

SWING BooksPure 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 sectionPages 336 – 358 in java software solutions 4th ed orPages 473-518 in the Big Java 1st ed.

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

SWING Component Hierarchy

Java.lang.ObjectJava.awt.Component

Java.awt.ContainerJavax.swing.JComponent

Page 208: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 194

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

SWING Components

JAppletJButtonJCkeckBoxJColorChooserJComboBoxJDesktopPaneJDialogJFileChooserJPopupMenuJProgressBarJRadioButton

JFrameJLabelJListJMenuJMenuBarJMenuItemJOptionPaneJPanelJPasswordFieldJScrollBarJSlider

JTableJTextAreaJTextPaneJTabbedPaneJSplitPaneJToggleButtonJToolBarJToolTipJTree

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

SWING Example

Page 209: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 195

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

SWING Example

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

SWING Example

Page 210: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 196

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

SWING Example

The following example illustrates 1. Checkboxes, radio buttons2. Fonts, bold, italics3. Borders4. Frames and Panels5. Combo boxes6. Frame titles7. GridLayout and containers8. Event notification9. General Code Format

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

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 x_loc = 0;private int y_loc = 0;

/*** Default Constructor* @author Jim Adams* @param None* @return Nothing*/public Tester01(){

x_loc = 100;y_loc = 100;

}Code tested 05/30/2005

Page 211: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 197

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

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 panelJPanel facenamePanel = createComboBox(); // combobox panelJPanel sizeGroupPanel = createCheckBoxes(); // check box panelJPanel styleGroupPanel = createRadioButtons(); // radio button panel

sampleField = new JLabel("Jim's Swing Test");setSampleFont();

controlPanel.setLayout(new GridLayout(4, 1)); // rows, colscontrolPanel.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

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

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

Page 212: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 198

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

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

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

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);

panel.add(smallButton);panel.add(mediumButton);panel.add(largeButton);panel.setBorder(new TitledBorder(new EtchedBorder(), "Size"));

return panel;}

Code tested 05/30/2005

Page 213: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 199

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

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

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

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

Page 214: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 200

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

SWING Example

What else could we have done with this class?1. Different borders2. Icon on top title bar3. Added Images4. Background colors5. Foreground colors6. Locked the physical size and location7. Watched the mouse8. Add tool bars9. Add tool tips10. Add menus11. Add other components, buttons, sliders, etc12. Set a different look and feel (Windows, Mac, etc)13. Used different layout managers ….

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

Frames and Windows

Primary WindowSecondary WindowPlain WindowUtility Window

Page 215: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 201

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

Frames and WindowsPrimary 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

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

Frames and WindowsSecondary 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.

Page 216: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 202

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

Frames and WindowsPlain 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-404December 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.

Page 217: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 203

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

Organizing Window Contents

PanelsScroll PanesTabbed PanesSplit Panes

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

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.

Page 218: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 204

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

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.

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

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 boxeshave 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.

Page 219: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 205

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

Organizing Window ContentsTabbed 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 componentsThe 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.

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

Organizing Window ContentsSplit 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

Page 220: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 206

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

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

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

Organizing Window ContentsBacking 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 windowThe JDesktopPane component is used to implement backing windows.

Page 221: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 207

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

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. Box Layout2. Border Layout3. Grid Layout4. GridBag Layout

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

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

Layout ManagementJim’s Hint:

1. Create JFrame Object2. Create JPanels Objects3. Create Border Layouts Objects4. Create Components5. Add Components to JPanels6. Add JPanels to JFrames7. Show the JFrame frame.setVisible(true);

Excellent online book by Sun Microsystemshttp://java.sun.com/products/jlf/ed2/book/

Page 222: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 208

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

Layout ManagementVarious Layout Managers

BorderLayoutBoxLayoutCardLayoutFlowLayoutGridBagLayoutGridLayoutSpringLayout

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

Layout Management

Page 223: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 209

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

Border Layout Border Layout places components into geographical-based positions like

center, north, west, south, eastpanel.add(textField, BorderLayout.SOUTH);

Content pane of frame has Border Layout by defaultframe.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

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

Card Layout

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

Page 224: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 210

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

Spring Layout

SpringLayout is a flexible layout managerIt 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

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

Grid LayoutLays 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)); // y, xpanel.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);

Page 225: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 211

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

Grid Bag LayoutLays 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); // border insetc.gridx = 1; c.gridy = 1;c.gridwidth = 1; // width in columnsc.gridheight = 1; // height in rowsc.weightx=1.0;c.weighty=1.0;grid.setConstraints(button, c);p0.add(button);

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

Grid Bag Layout Example (1 of 4)

Lays out components in rows and columns Allows components to have the different sizes 1. Container container = null;2. container = this.getContentPane();3. GridBagLayout grid = new GridBagLayout();4. container.setLayout(grid);5. GridBagConstraints c = new GridBagConstraints();6. c.fill = GridBagConstraints.BOTH;7. c.insets = new Insets(5,5,5,5); // border inset8. c.gridx = 1; 9. c.gridy = 1;10. c.gridwidth = 1;11. c.gridheight = 1;12. c.weightx=1.0;13. c.weighty=1.0;14. JButton button = new JButton(“Button1”);15. grid.setConstraints(button, c);16. container.add(button);

Page 226: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 212

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

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);

.

.

.

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

Grid Bag Layout Example (3 of 4)

// make the first buttonc.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 buttonc.gridx = 2; c.gridy = 2;c.gridwidth= 1;c.gridheight=1;makeButton("Button2", grid, c);

Page 227: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 213

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

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);}

}

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

Page 228: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 214

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

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.

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

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

Page 229: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 215

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

Box Layout

Glue Use this to specify where excess space in a layout should go. Think of it as semi-

wet glue — stretchy and expandable, yet taking up no space unless you pullapart 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);

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

Combining Layout Managers

Page 230: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 216

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

Radio ButtonsRadio buttons are mutually exclusive Button group turns one button off when the next one is turned onsButton = 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 selectedif (sButton.isSelected()) . . .

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

Radio ButtonsRadio 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);

Page 231: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 217

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

Radio Buttons ListenersJRadioButton radio1 = new JRadioButton(“Take Midterm”);JRadioButton radio2 = 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

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

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

Page 232: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 218

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

Check Boxes

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

Don't place into button group

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

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

Check Boxes

Whenever a check box is selected or deselected an event of type ItemEvent is firedMethods from the ItemEvent class

public Object getItem(); // retrieves the item labelpublic ItemSelectable getItemSelectable()public int getStateChanged()

Page 233: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 219

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

Combo Boxes Use less space than radio buttons Users can type other values “Combo” between list selection and text fieldJComboBox faceName = new JComboBox();faceName.addItem("Serif");faceName.addItem("SansSerif");faceName.addItem("Monospaced");

Get user selectionsel = (String)faceName.getSelectedItem();

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

Java Menus Jim’s Hint:1. Declare the Menu Bars, Menus and Menu Items2. Add menu items to the menus3. Add menus to the menu bar4. Add menu bar to the JFrame5. Add action Listeners to the menu Items6. Add Hot Keys to menu items

Page 234: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 220

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

Menu ItemsAdd menu bar to frame

JMenuBar bar = new JMenuBar();frame.setJMenuBar(bar);

Add menus to the menu barJMenu fileMenu = new JMenu("File");bar.add(fileMenu);

Add menu items to the menuJMenuItem fileNew = new JMenuItem("New");JMenuItem fileOpen = new JMenuItem(“Open");fileMenu.add(fileNew);fileMenu.add(fileOpen);

Add action listener to the menu itemfileNew.addActionListener(new fileNewListener());fileOpen.addActionListener(new fileOpenListener())

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

Menu ComponentsJMenuBar MainMenu = new JMenuBar();

JMenu FileMenu = new JMenu("File");JMenu EditMenu = new JMenu("Edit");JMenu ViewMenu = new JMenu("View");JMenu BuildMenu = new JMenu("Build");JMenu ToolsMenu = new JMenu("Tools");JMenu HelpMenu = new JMenu("Help");

JMenuItem MI_New = new JMenuItem("New");JMenuItem MI_Close = new JMenuItem("Close");JMenuItem MI_Open = new JMenuItem("Open");JMenuItem MI_Save = new JMenuItem("Save");JMenuItem MI_SaveAs = new JMenuItem("Save As");JMenuItem MI_Print = new JMenuItem("Print");JMenuItem MI_Exit = new JMenuItem("Exit");JMenuItem MI_Cut = new JMenuItem("Cut");

Page 235: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 221

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

Menu ItemsFileMenu.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);

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

Adding Menu ItemsToolsMenu.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 ActionsMI_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));

Page 236: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 222

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

Setting Menu Item FontFont 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);

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

Constructing a SliderConstructorsJSlider js = new JSlider();

Has range (0,100) with initial value of 50JSlider(int min, int max, int value);

Can specify range and initial valueJSlider(int orientation, int min, int max, int

value);Can use JSlider.HORIZONTAL and JSlider.VERTICAL

Page 237: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 223

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

Constructing a SliderCan set minimum, maximum, paint the tick marks, major

spacing and minor spacing of ticks.slider.setMajorTickSpacing(int);slider.setMinorTickSpacing(int);

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

Listening to a Slider

Look for “addxxxListener”:void addChangeListener(ChangeListenerlisten)What is a change listener? It has a single methodvoid stateChanged(ChangeEvent e)How can we tell new slider setting?int getValue()Listener method reads all slider values and updates color

Page 238: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 224

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

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, babyJFrame frame = new JFrame();frame.setTitle("Slider Test");frame.setSize(350,160); // x,yframe.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);

Code Tested 08/25/2004

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

Listening to a Slider (2 of 2)BorderLayout maingrid = new BorderLayout(2,2);

JPanel panel = new JPanel();panel.setLayout(maingrid); // border layoutpanel.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

Page 239: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 225

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

Java Example Panels

Image courtesy Sun Microsystems

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

Java Example Panels

Images courtesy Sun Microsystems

Page 240: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 226

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

File ChooserJava File Chooser

View Sample Code

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

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

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

Code tested 08/25/2004

Page 241: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 227

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

File Chooserstatic java.lang.String APPROVE_LABELstatic int APPROVE_OPTIONstatic java.lang.String CANCEL_LABELstatic int CANCEL_OPTIONstatic int ERROR_OPTION

getCurrentDirectory() Returns the currently displayed directory. getFileFilter() Returns the currently selected file filter. getFileSelectionMode() Returns the current file-selection mode. getSelectedFile() Get the File selected by the user.

chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);

chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);

chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);

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

Color ChooserConstructorspublic JColorChooser()public JColorChooser(Color initial color);

Page 242: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 228

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

Color Chooser Exampleimport java.awt.*;import javax.swing.*;import java.awt.event.*;

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

View Sample Code

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

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 );

Page 243: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 229

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

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

}

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

Can Also Do Split Panes

Page 244: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 230

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

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);

Jim’s Hint:Declare the component such as a button, combo box, etcSet the component attributesSet the property addActionListener to point to an inner classAdd the inner class with an actionPerformed methodCall a method from the inner class method

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

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

Page 245: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 231

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

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

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

Many Other Swing Elements

JAppletJButtonJCkeckBoxJColorChooserJComboBoxJDesktopPaneJDialogJFileChooserJPopupMenuJProgressBarJRadioButton

JFrameJLabelJListJMenuJMenuBarJMenuItemJOptionPaneJPanelJPasswordFieldJScrollBarJSlider

JTableJTextAreaJTextPaneJTabbedPaneJSplitPaneJToggleButtonJToolBarJToolTipJTree

Page 246: DS Presentation

Data Structures and Algorithms By Jim Adams

Page-: 232

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

Swing GUI Summary

Graphical User Interfaces

Summary1. Understand how GUI components are added to a

container2. Layout managers3. Common user interface components, buttons, combo

boxes, radio dials and menus4. Handle events from user components