Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "Android How to Program, 2/e © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved."— Presentation transcript:

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

2

3

4

5  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 1992-2015 by Pearson Education, Inc. All Rights Reserved.

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

7  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 1992-2015 by Pearson Education, Inc. All Rights Reserved.

8

9  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 1992-2015 by Pearson Education, Inc. All Rights Reserved.

10  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 1992-2015 by Pearson Education, Inc. All Rights Reserved.

11  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 1992-2015 by Pearson Education, Inc. All Rights Reserved.

12

13  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 1992-2015 by Pearson Education, Inc. All Rights Reserved.

14  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 1992-2015 by Pearson Education, Inc. All Rights Reserved.

15  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 1992-2015 by Pearson Education, Inc. All Rights Reserved.

16

17

18

19

20  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 1992-2015 by Pearson Education, Inc. All Rights Reserved.

21  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 1992-2015 by Pearson Education, Inc. All Rights Reserved.

22

23

24

25

26

27  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 1992-2015 by Pearson Education, Inc. All Rights Reserved.

28  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 1992-2015 by Pearson Education, Inc. All Rights Reserved.

29

30

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

32

33  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 1992-2015 by Pearson Education, Inc. All Rights Reserved.

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

35

36

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

38

39

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

41  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 1992-2015 by Pearson Education, Inc. All Rights Reserved.

42  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 1992-2015 by Pearson Education, Inc. All Rights Reserved.

43

44

45  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 1992-2015 by Pearson Education, Inc. All Rights Reserved.

46  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 1992-2015 by Pearson Education, Inc. All Rights Reserved.

47  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 1992-2015 by Pearson Education, Inc. All Rights Reserved.

48

49

50

51

52  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 1992-2015 by Pearson Education, Inc. All Rights Reserved.

53  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 1992-2015 by Pearson Education, Inc. All Rights Reserved.

54

55  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 1992-2015 by Pearson Education, Inc. All Rights Reserved.

56  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 1992-2015 by Pearson Education, Inc. All Rights Reserved.

57  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 1992-2015 by Pearson Education, Inc. All Rights Reserved.

58  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 1992-2015 by Pearson Education, Inc. All Rights Reserved.

59  The complete hierarchy of classes in package java.io can be viewed in the online documentation at  http://docs.oracle.com/javase/7/docs/ 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 1992-2015 by Pearson Education, Inc. All Rights Reserved.

60  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 1992-2015 by Pearson Education, Inc. All Rights Reserved.

61  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 1992-2015 by Pearson Education, Inc. All Rights Reserved.

62  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  http://download.oracle.com/javase/6 / docs/ api/java/io/File.html http://download.oracle.com/javase/6 / docs/ api/java/io/File.html © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved.

63

64

65  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 1992-2015 by Pearson Education, Inc. All Rights Reserved.

66  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 1992-2015 by Pearson Education, Inc. All Rights Reserved.

67  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 1992-2015 by Pearson Education, Inc. All Rights Reserved.

68  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 1992-2015 by Pearson Education, Inc. All Rights Reserved.

69

70  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 1992-2015 by Pearson Education, Inc. All Rights Reserved.

71  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 1992-2015 by Pearson Education, Inc. All Rights Reserved.

72

73  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 1992-2015 by Pearson Education, Inc. All Rights Reserved.

74

75

76  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 1992-2015 by Pearson Education, Inc. All Rights Reserved.

77  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 1992-2015 by Pearson Education, Inc. All Rights Reserved.

78

79

80

81  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 1992-2015 by Pearson Education, Inc. All Rights Reserved.

82  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 1992-2015 by Pearson Education, Inc. All Rights Reserved.

83  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 1992-2015 by Pearson Education, Inc. All Rights Reserved.

84  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 http://download.oracle.com/javase/6/docs/api/java/ util/concurrent/package-summary.html © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved.

85  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 1992-2015 by Pearson Education, Inc. All Rights Reserved.

86  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 1992-2015 by Pearson Education, Inc. All Rights Reserved.

87

88  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 1992-2015 by Pearson Education, Inc. All Rights Reserved.

89

90

91

92  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 1992-2015 by Pearson Education, Inc. All Rights Reserved.

93  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 1992-2015 by Pearson Education, Inc. All Rights Reserved.

94

95  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 1992-2015 by Pearson Education, Inc. All Rights Reserved.

96

97

98

99

100

101

102


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

Similar presentations


Ads by Google