Android How to Program, 2/e © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved.

Slides:



Advertisements
Similar presentations
Introduction to Java 2 Programming Lecture 5 The Collections API.
Advertisements

Transparency No. 1 Java Collection API : Built-in Data Structures for Java.
JAVA Programming (Session 7) When you are willing to make sacrifices for a great cause, you will never be alone. Instructor:
Java How to Program, 9/e CET 3640 Professor: Dr. José M. Reyes Álamo © Copyright by Pearson Education, Inc. All Rights Reserved.
 2007 Pearson Education, Inc. All rights reserved. 1 Ch23 Multithreading: OBJECTIVES In this chapter you will learn:  What threads are and why they are.
1 L43 Collections (3). 2 OBJECTIVES  To use the collections framework interfaces to program with collections polymorphically.  To use iterators to “walk.
1 L41 Collections (1). 2 OBJECTIVES  What collections are.  To use class Arrays for array manipulations.  To use the collections framework (prepackaged.
Java Collections. Lecture Objectives To understand the concepts of Java collections To be able to implement Java programs based on Collections.
24-Jun-15 Introduction to Collections. 2 Collections A collection is a structured group of objects Java 1.2 introduced the Collections Framework Collections.
© The McGraw-Hill Companies, 2006 Chapter 17 The Java Collections Framework.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L15 (Chapter 22) Java Collections.
Slides prepared by Rose Williams, Binghamton University Chapter 10 File I/O.
CS102--Object Oriented Programming Lecture 14: – File I/O BufferedReader The File class Write to /read from Binary files Copyright © 2008 Xiaoyan Li.
Chapter 19 Java Data Structures
Java How to Program, 9/e CET 3640 Professor: Dr. Reyes Álamo © Copyright by Pearson Education, Inc. All Rights Reserved.
SEG4110 – Advanced Software Design and Reengineering TOPIC G Java Collections Framework.
Files and Streams (part 2) 1 -Based on slides from Deitel & Associates, Inc. - Revised by T. A. Yang.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Introduction to Java Appendix A. Appendix A: Introduction to Java2 Chapter Objectives To understand the essentials of object-oriented programming in Java.
Java Programming: Advanced Topics 1 Collections and Wealth of Utilities.
Files and Streams 1 -Based on slides from Deitel & Associates, Inc. - Revised by T. A. Yang.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 22 Java Collections.
Collections F The limitations of arrays F Java Collection Framework hierarchy  Use the Iterator interface to traverse a collection  Set interface, HashSet,
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 22 Java Collections.
Java™ How to Program, 9/e Presented by: Dr. José M. Reyes Álamo © Copyright by Pearson Education, Inc. All Rights Reserved.
CIS 270—Application Development II Chapter 14—Files and Streams.
Java How to Program, 9/e © Copyright by Pearson Education, Inc. All Rights Reserved.
Stream: an object that either delivers data to its destination (screen, file, etc.) or that takes data from a source (keyboard, file, etc.) –it acts as.
1 Java's Collection Framework By Rick Mercer with help from The Java Tutorial, The Collections Trail, by Joshua BlockThe Collections Trail.
(c) University of Washington14-1 CSC 143 Java Collections.
Jan 12, 2012 Introduction to Collections. 2 Collections A collection is a structured group of objects Java 1.2 introduced the Collections Framework Collections.
GENERIC COLLECTIONS. Type-Wrapper Classes  Each primitive type has a corresponding type- wrapper class (in package java.lang).  These classes are called.
111 © 2002, Cisco Systems, Inc. All rights reserved.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Java How to Program, 8/e © by Pearson Education, Inc. All Rights Reserved.
Generics and Collections. Introduction Generics New feature of J2SE 5.0 Provide compile-time type safety Catch invalid types at compile time Generic methods.
Chapter 18 Java Collections Framework
Java™ How to Program, 10/e © Copyright by Pearson Education, Inc. All Rights Reserved.
Visual Basic 2010 How to Program © by Pearson Education, Inc. All Rights Reserved.
Multithreading Chapter Introduction Consider ability of human body to ___________ –Breathing, heartbeat, chew gum, walk … In many situations we.
CMSC 202 Text File I/O. Aug 8, Text Files and Binary Files Files that are designed to be read by human beings, and that can be read or written with.
Collections Data structures in Java. OBJECTIVE “ WHEN TO USE WHICH DATA STRUCTURE ” D e b u g.
 Pearson Education, Inc. All rights reserved Files and Streams.
Object Serialization.  When the data was output to disk, certain information was lost, such as the type of each value.  If the value "3" is read from.
Sections © Copyright by Pearson Education, Inc. All Rights Reserved.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Introduction to Scripting.
1 Exceptions Exception handling – Exception Indication of problem during execution – E.g., divide by zero – Chained exceptions Uses of exception handling.
Priority Queues. Priority Queue ADT A priority queue stores a collection of entries Each entry is a pair (key, value) Main methods of the Priority Queue.
Slides prepared by Rose Williams, Binghamton University Chapter 16 Collections and Iterators.
CMSC 202 Containers and Iterators. Container Definition A “container” is a data structure whose purpose is to hold objects. Most languages support several.
Java How to Program, 9/e © Copyright by Pearson Education, Inc. All Rights Reserved.
JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN © 2012 Pearson Education, Inc., Upper Saddle River,
University of Limerick1 Collections The Collection Framework.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 21 Sets and Maps.
JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN © 2012 Pearson Education, Inc., Upper Saddle River,
Collections Dwight Deugo Nesa Matic
Concurrency (Threads) Threads allow you to do tasks in parallel. In an unthreaded program, you code is executed procedurally from start to finish. In a.
3-1 Java's Collection Framework Another use of polymorphism and interfaces Rick Mercer.
(C) 2010 Pearson Education, Inc. All rights reserved. Java How to Program, 8/e.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java From Control Structures through Data Structures by.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
Collections ABCD ABCD Head Node Tail Node array doubly linked list Traditional Arrays and linked list: Below is memory representation of traditional.
Chapter 21 Sets and Maps Jung Soo (Sue) Lim Cal State LA.
Chapter 19 Java Data Structures
Chapter 20 Generic Classes and Methods
I/O Basics.
MSIS 670: Object-Oriented Software Engineering
Chapter 15 Files, Streams and Object Serialization
Chapter 16 Generic Collections
Presentation transcript:

Android How to Program, 2/e © Copyright by Pearson Education, Inc. All Rights Reserved.

 Sections J.2–J.9 present an overview of the Java collections framework and several examples of working with various collections that we use in our Android apps.  Sections J.10–J.12 introduce file and stream concepts, overview method of class File and discuss object- serialization for writing entire objects to streams and reading entire objects from streams.  Sections J.13–J.17 present the fundamentals of multithreading. © Copyright by Pearson Education, Inc. All Rights Reserved.

 Java collections framework ◦ prebuilt data structures ◦ interfaces and methods for manipulating those data structures © Copyright by Pearson Education, Inc. All Rights Reserved.

 A collection is a data structure—actually, an object— that can hold references to other objects. ◦ Usually, collections contain references to objects that are all of the same type.  Figure J.1 lists some of the interfaces of the collections framework.  Package java.util. © Copyright by Pearson Education, Inc. All Rights Reserved.

 Each primitive type has a corresponding type-wrapper class (in package java.lang ). ◦ Boolean, Byte, Character, Double, Float, Integer, Long and Short.  Each type-wrapper class enables you to manipulate primitive-type values as objects.  Collections cannot manipulate variables of primitive types. ◦ They can manipulate objects of the type-wrapper classes, because every class ultimately derives from Object. © Copyright by Pearson Education, Inc. All Rights Reserved.

 Each of the numeric type-wrapper classes— Byte, Short, Integer, Long, Float and Double — extends class Number.  The type-wrapper classes are final classes, so you cannot extend them.  Primitive types do not have methods, so the methods related to a primitive type are located in the corresponding type-wrapper class. © Copyright by Pearson Education, Inc. All Rights Reserved.

 Interface Collection is the root interface from which interfaces Set, Queue and List are derived.  Interface Set defines a collection that does not contain duplicates.  Interface Queue defines a collection that represents a waiting line.  Interface Collection contains bulk operations for adding, clearing and comparing objects in a collection.  A Collection can be converted to an array.  Interface Collection provides a method that returns an Iterator object, which allows a program to walk through the collection and remove elements from the collection during the iteration.  Class Collections provides static methods that search, sort and perform other operations on collections. © Copyright by Pearson Education, Inc. All Rights Reserved.

 A List is a Collection that can contain duplicate elements.  List indices are zero based.  In addition to the methods inherited from Collection, interface List provides methods for manipulating elements via their indices, manipulating a specified range of elements, searching for elements and obtaining a ListIterator to access the elements.  Interface List is implemented by several classes, including ArrayList and LinkedList. © Copyright by Pearson Education, Inc. All Rights Reserved.

 Class ArrayList is a resizable-array implementation of List.  Inserting an element between existing elements of an ArrayList is an inefficient operation.  A LinkedList enables efficient insertion (or removal) of elements in the middle of a collection. © Copyright by Pearson Education, Inc. All Rights Reserved.

 List method add adds an item to the end of a list.  List method size retursn the number of elements.  List method get retrieves an individual element’s value from the specified index.  Collection method iterator gets an Iterator for a Collection.  Iterator- method hasNext determines whether a Collection contains more elements. ◦ Returns true if another element exists and false otherwise.  Iterator method next obtains a reference to the next element.  Collection method contains determine whether a Collection contains a specified element.  Iterator method remove removes the current element from a Collection. © Copyright by Pearson Education, Inc. All Rights Reserved.

 List method addAll appends all elements of a collecton to the end of a List.  List method listIterator gets A List ’s bidirectional iterator.  String method toUpperCase gets an uppercase version of a String.  List-Iterator method set replaces the current element to which the iterator refers with the specified object.  String method toLowerCase returns a lowercase version of a String.  List method subList obtaina a portion of a List. ◦ This is a so-called range-view method, which enables the program to view a portion of the list. © Copyright by Pearson Education, Inc. All Rights Reserved.

 List method clear remove the elements of a List.  List method size returns the number of items in the List.  ListIterator method hasPrevious determines whether there are more elements while traversing the list backward.  ListIterator method previous gets the previous element from the list. © Copyright by Pearson Education, Inc. All Rights Reserved.

 Class Arrays provides static method asList to view an array as a List collection. ◦ A List view allows you to manipulate the array as if it were a list. ◦ This is useful for adding the elements in an array to a collection and for sorting array elements.  Any modifications made through the List view change the array, and any modifications made to the array change the List view.  The only operation permitted on the view returned by asList is set, which changes the value of the view and the backing array. ◦ Any other attempts to change the view result in an UnsupportedOperationException.  List method toArray gets an array from a List collection. © Copyright by Pearson Education, Inc. All Rights Reserved.

 LinkedList method addLast adds an element to the end of a List.  LinkedList method add also adds an element to the end of a List.  LinkedList method addFirst adds an element to the beginning of a List. © Copyright by Pearson Education, Inc. All Rights Reserved.

 Class Collections provides several high- performance algorithms for manipulating collection elements.  The algorithms (Fig. J.5) are implemented as static methods. © Copyright by Pearson Education, Inc. All Rights Reserved.

 Method sort sorts the elements of a List ◦ The elements must implement the Comparable interface. ◦ The order is determined by the natural order of the elements’ type as implemented by a compareTo method. ◦ Method compareTo is declared in interface Comparable and is sometimes called the natural comparison method. ◦ The sort call may specify as a second argument a Comparator object that determines an alternative ordering of the elements. © Copyright by Pearson Education, Inc. All Rights Reserved.

 The static Collections method reverseOrder returns a Comparator object that orders the collection’s elements in reverse order. © Copyright by Pearson Education, Inc. All Rights Reserved.

 Figure J.7 sorts a list using the custom Comparator class TimeComparator. © Copyright by Pearson Education, Inc. All Rights Reserved.

 Method shuffle randomly orders a List ’s elements. © Copyright by Pearson Education, Inc. All Rights Reserved.

 Interface Queue extends interface Collection and provides additional operations for inserting, removing and inspecting elements in a queue.  You can view the details of interface Queue and the list of classes that implement it at docs.oracle.com/javase/7/docs/api/ index.html?java/util/Queue.html © Copyright by Pearson Education, Inc. All Rights Reserved.

 A Set is an unordered Collection of unique elements (i.e., no duplicate elements).  The collections framework contains several Set implementations, including HashSet and TreeSet.  HashSet stores its elements in a hash table, and TreeSet stores its elements in a tree. © Copyright by Pearson Education, Inc. All Rights Reserved.

 The collections framework also includes the SortedSet interface (which extends Set ) for sets that maintain their elements in sorted order.  Class TreeSet implements SortedSet. © Copyright by Pearson Education, Inc. All Rights Reserved.

 Map s associate keys to values. ◦ The keys in a Map must be unique, but the associated values need not be. ◦ If a Map contains both unique keys and unique values, it is said to implement a one-to-one mapping. ◦ If only the keys are unique, the Map is said to implement a many-to-one mapping—many keys can map to one value. © Copyright by Pearson Education, Inc. All Rights Reserved.

 Three of the several classes that implement interface Map are Hashtable, HashMap and TreeMap, and maps are used extensively in Android.  Hashtable s and HashMap s store elements in hash tables, and TreeMap s store elements in trees.  Interface SortedMap extends Map and maintains its keys in sorted order—either the elements’ natural order or an order specified by a Comparator.  Class TreeMap implements SortedMap. © Copyright by Pearson Education, Inc. All Rights Reserved.

 Map method containsKey determines whether a key is in a map.  Map method put creates a new entry in the map or replaces an existing entry’s value. ◦ Method put returns the key’s prior associated value, or null if the key was not in the map.  Map method get obtain the specified key’s associated value in the map.  HashMap method keySet returns a set of the keys.  Map method size returns the number of key/value pairs in the Map.  Map method isEmpty returns a boolean indicating whether the Map is empty. © Copyright by Pearson Education, Inc. All Rights Reserved.

 Java views each file as a sequential stream of bytes (Fig. J.10).  Every operating system provides a mechanism to determine the end of a file, such as an end-of-file marker or a count of the total bytes in the file that is recorded in a system-maintained administrative data structure.  A Java program simply receives an indication from the operating system when it reaches the end of the stream © Copyright by Pearson Education, Inc. All Rights Reserved.

 Streams can be used to input and output data as bytes or characters.  Streams that input and output bytes are known as byte- based streams, representing data in its binary format.  Streams that input and output characters are known as character-based streams, representing data as a sequence of characters.  Files that are created using byte-based streams are referred to as binary files.  Files created using character-based streams are referred to as text files. Text files can be read by text editors.  Binary files are read by programs that understand the specific content of the file and the ordering of that content. © Copyright by Pearson Education, Inc. All Rights Reserved.

 A Java program opens a file by creating an object and associating a stream of bytes or characters with it. ◦ Can also associate streams with different devices.  Java creates three stream objects when a program begins executing ◦ System.in (the standard input stream object) normally inputs bytes from the keyboard ◦ System.out (the standard output stream object) normally outputs character data to the screen ◦ System.err (the standard error stream object) normally outputs character-based error messages to the screen.  Class System provides methods setIn, setOut and setErr to redirect the standard input, output and error streams, respectively. © Copyright by Pearson Education, Inc. All Rights Reserved.

 Java programs perform file processing by using classes from package java.io.  Includes definitions for stream classes ◦ FileInputStream (for byte-based input from a file) ◦ FileOutputStream (for byte-based output to a file) ◦ FileReader (for character-based input from a file) ◦ FileWriter (for character-based output to a file)  You open a file by creating an object of one these stream classes. The object’s constructor opens the file. © Copyright by Pearson Education, Inc. All Rights Reserved.

 Can perform input and output of objects or variables of primitive data types without having to worry about the details of converting such values to byte format.  To perform such input and output, objects of classes ObjectInputStream and ObjectOutputStream can be used together with the byte-based file stream classes FileInputStream and FileOutputStream. © Copyright by Pearson Education, Inc. All Rights Reserved.

 The complete hierarchy of classes in package java.io can be viewed in the online documentation at  api/java/io/package-tree.html  Character-based input and output can be performed with classes Scanner and Formatter. ◦ Class Scanner is used extensively to input data from the keyboard. This class can also read data from a file. ◦ Class Formatter enables formatted data to be output to any text-based stream in a manner similar to method System.out.printf. © Copyright by Pearson Education, Inc. All Rights Reserved.

 Class File provides information about files and directories.  File objects are used frequently with objects of other java.io classes to specify files or directories to manipulate. © Copyright by Pearson Education, Inc. All Rights Reserved.

 Class File provides four constructors.  The one with a String argument specifies the name of a file or directory to associate with the File object. ◦ The name can contain path information as well as a file or directory name. ◦ A file or directory’s path specifies its location on disk. ◦ An absolute path contains all the directories, starting with the root directory, that lead to a specific file or directory. ◦ A relative path normally starts from the directory in which the application began executing and is therefore “relative” to the current directory. © Copyright by Pearson Education, Inc. All Rights Reserved.

 The constructor with two String arguments specifies an absolute or relative path and the file or directory to associate with the File object.  The constructor with File and String arguments uses an existing File object that specifies the parent directory of the file or directory specified by the String argument.  The fourth constructor uses a URI object to locate the file. ◦ A Uniform Resource Identifier (URI) is a more general form of the Uniform Resource Locators (URLs) that are used to locate websites.  Figure J.11 lists some common File methods. The  / docs/ api/java/io/File.html / docs/ api/java/io/File.html © Copyright by Pearson Education, Inc. All Rights Reserved.

 Java provides object serialization for writing entire objects to a stream and reading entire objects from a stream.  A serialized object is represented as a sequence of bytes that includes the object’s data and its type information.  After a serialized object has been written into a file, it can be read from the file and deserialized to recreate the object in memory. © Copyright by Pearson Education, Inc. All Rights Reserved.

 Classes ObjectInputStream and ObjectOutputStream, which respectively implement the ObjectInput and ObjectOutput interfaces, enable entire objects to be read from or written to a stream.  To use serialization with files, initialize ObjectInputStream and ObjectOutputStream objects with FileInputStream and FileOutputStream objects. © Copyright by Pearson Education, Inc. All Rights Reserved.

 ObjectOutput interface method writeObject takes an Object as an argument and writes its information to an OutputStream.  A class that implements ObjectOuput (such as ObjectOutputStream ) declares this method and ensures that the object being output implements Serializable.  ObjectInput interface method readObject reads and returns a reference to an Object from an InputStream. ◦ After an object has been read, its reference can be cast to the object’s actual type. © Copyright by Pearson Education, Inc. All Rights Reserved.

 Operating systems on single-processor computers create the illusion of concurrent execution by rapidly switching between activities, but on such computers only a single instruction can execute at once.  Java makes concurrency available to you through the language and APIs.  You specify that an application contains separate threads of execution ◦ each thread has its own method-call stack and program counter ◦ can execute concurrently with other threads while sharing applicationwide resources such as memory with them.  This capability is called multithreading. © Copyright by Pearson Education, Inc. All Rights Reserved.

 Programming concurrent applications is difficult and error prone.  If you must use synchronization in a program, you should use existing classes from the Concurrency APIs that manage synchronization for you. © Copyright by Pearson Education, Inc. All Rights Reserved.

 A Runnable object represents a “task” that can execute concurrently with other tasks.  The Runnable interface declares the single method run, which contains the code that defines the task that a Runnable object should perform.  When a thread executing a Runnable is created and started, the thread calls the Runnable object’s run method, which executes in the new thread. © Copyright by Pearson Education, Inc. All Rights Reserved.

 Class PrintTask (Fig. J.12) implements Runnable (line 5), so that multiple PrintTasks can execute concurrently.  Thread static method sleep places a thread in the timed waiting state for the specified amount of time. ◦ Can throw a checked exception of type InterruptedException if the sleeping thread’s interrupt method is called.  The code in main executes in the main thread, a thread created by the JVM.  The code in the run method of PrintTask executes in the threads created in main.  When method main terminates, the program itself continues running because there are still threads that are alive. ◦ The program will not terminate until its last thread completes execution. © Copyright by Pearson Education, Inc. All Rights Reserved.

 Recommended that you use the Executor interface to manage the execution of Runnable objects for you. ◦ Typically creates and manages a group of threads called a thread pool to execute Runnable s.  Executor s can reuse existing threads and can improve performance by optimizing the number of threads.  Executor method execute accepts a Runnable as an argument.  An Executor assigns every Runnable passed to its execute method to one of the available threads in the thread pool.  If there are no available threads, the Executor creates a new thread or waits for a thread to become available. © Copyright by Pearson Education, Inc. All Rights Reserved.

 The ExecutorService interface extends Executor and declares methods for managing the life cycle of an Executor.  An object that implements this interface can be created using static methods declared in class Executors.  Executors method newCachedThreadPool returns an ExecutorService that creates new threads as they’re needed by the application.  ExecutorService method shutdown notifies the ExecutorService to stop accepting new tasks, but continues executing tasks that have already been submitted. © Copyright by Pearson Education, Inc. All Rights Reserved.

 When multiple threads share an object and it is modified by one or more of them, indeterminate results may occur unless access to the shared object is managed properly.  The problem can be solved by giving only one thread at a time exclusive access to code that manipulates the shared object. ◦ During that time, other threads desiring to manipulate the object are kept waiting. ◦ When the thread with exclusive access to the object finishes manipulating it, one of the threads that was waiting is allowed to proceed.  This process, called thread synchronization, coordinates access to shared data by multiple concurrent threads. ◦ Ensures that each thread accessing a shared object excludes all other threads from doing so simultaneously—this is called mutual exclusion. © Copyright by Pearson Education, Inc. All Rights Reserved.

 A common way to perform synchronization is to use Java’s built-in monitors. ◦ Every object has a monitor and a monitor lock (or intrinsic lock). ◦ Can be held by a maximum of only one thread at any time. ◦ A thread must acquire the lock before proceeding with the operation. ◦ Other threads attempting to perform an operation that requires the same lock will be blocked.  To specify that a thread must hold a monitor lock to execute a block of code, the code should be placed in a synchronized statement. ◦ Said to be guarded by the monitor lock © Copyright by Pearson Education, Inc. All Rights Reserved.

 The synchronized statements are declared using the synchronized keyword:  synchronized ( object ) { statements } // end synchronized statement  where object is the object whose monitor lock will be acquired ◦ object is normally this if it’s the object in which the synchronized statement appears.  When a synchronized statement finishes executing, the object’s monitor lock is released.  Java also allows synchronized methods. © Copyright by Pearson Education, Inc. All Rights Reserved.

 The collections from the java.util.concurrent package are specifically designed and optimized for use in programs that share collections among multiple threads.  For more information, visit util/concurrent/package-summary.html © Copyright by Pearson Education, Inc. All Rights Reserved.

 All Swing applications have an event dispatch thread, to handle interactions with the application’s GUI components.  All tasks that require interaction with an application’s GUI are placed in an event queue and are executed sequentially by the event dispatch thread.  Swing GUI components are not thread safe.  Thread safety in GUI applications is achieved by ensuring that Swing components are accessed from the event dispatch thread. ◦ Called thread confinement. © Copyright by Pearson Education, Inc. All Rights Reserved.

 Class SwingWorker (in package javax.swing ) perform long-running tasks in a worker thread and to update Swing components from the event dispatch thread based on the tasks’ results. ◦ I mplements the Runnable interface, meaning that a SwingWorker object can be scheduled to execute in a separate thread.  Some common SwingWorker methods are described in Fig. J.14. © Copyright by Pearson Education, Inc. All Rights Reserved.

 Class BackgroundCalculator (Fig. J.15) extends SwingWorker (line 8), overriding the methods doInBackground and done.  Method doInBackground (lines 21–24) computes the nth Fibonacci number in a worker thread and returns the result.  Method done (lines 27–43) displays the result in a JLabel. © Copyright by Pearson Education, Inc. All Rights Reserved.

 SwingWorker is a generic class.  The first type parameter indicates the type returned by the doInBackground method; the second indicates the type that is passed between the publish and process methods to handle intermediate results. ◦ Since we do not use publish and process in this example, we simply use Object as the second type parameter.  When method execute is called on a BackgroundCalculator object, the object is scheduled for execution in a worker thread.  Method doInBackground is called from the worker thread and invokes the fibonacci method (lines 46–52), passing instance variable n as an argument (line 23). ◦ When fibonacci returns, method doInBackground returns the result. © Copyright by Pearson Education, Inc. All Rights Reserved.

 After doInBackground returns, method done is called from the event dispatch thread. ◦ This method attempts to set the result JLabel to the return value of doInBackground by calling method get to retrieve the return value.  Method get waits for the result to be ready if necessary, but since we call it from method done, the computation will be complete before get is called. © Copyright by Pearson Education, Inc. All Rights Reserved.

 Class FibonacciNumbers (Fig. J.16) displays a window containing two sets of GUI components—one set to compute a Fibonacci number in a worker thread and another to get the next Fibonacci number in response to the user’s clicking a JButton. © Copyright by Pearson Education, Inc. All Rights Reserved.