20145326 "Java Program Design" The 5th Week study summary textbook Learning content Summary
Eighth Chapter
I. Grammar and inheritance structure
1. Using try, catch
When we write a program there are always errors caused by unexpected conditions, and errors in Java are rendered as objects of various subclass instances of java.lang.Throwable. You can do some processing for this error as long as you can catch the object that is wrapped incorrectly. All errors in Java are packaged as objects, and if you want, you can try (try) catch (catch) to represent the wrong object and do some processing. For example, in the book's 228-page code, where the Try,catch syntax is used, the JVM tries to execute the program code in the try block. If an error occurs, the execution process jumps off the point of the error and then compares the type declared in the catch parenthesis, conforms to the type of the wrong object being thrown, and executes the code in the catch block if it is. After executing the catch block, if there is no other code, the program ends. The 229-page example shows how to use try and catch to display a more friendly error message when an error occurs, and the error can be captured to try to recover the program's normal execution process. It is also mentioned in the book that Java is not encouraged to capture inputmismatchexception in the design of exception handling.
2. Exception Inheritance Schema
In the previous average example, a try, catch statement could be compiled and executed. Why are the 230-page examples compiling errors in the book? There are two ways to resolve this error message, one is to use try, catch to package System.in.read (), and two to declare throws Java.io.IOException next to the main () method. In simple terms, the compiler thinks that it is possible to make an error when calling System.in.read (), requiring you to explicitly process the information in the program. Errors are wrapped as objects that are all java.lang.Throwable, so the design Error object inherits from the class, and Throwable defines the method of getting the error message, the stack trace, etc. He has two sub-categories: Java.lang.Error and Java.lang.Exception. Error and its subclasses represent serious system errors, such as hardware-level errors, JVM errors, or low memory issues. Although you can also use try, catch to handle the error object, it is not recommended. When a serious system error occurs, Java itself is unable to recover. When the error object is thrown, it is basically not processed, either propagated to the JVM, or the log information is left at most. If the Throwable object is thrown, and no catch in the program catches the wrong object and is finally captured by the JVM, the JVM basically handles displaying the message packaged by the wrong object and interrupts the program. Error in the design of the program itself, it is recommended to use exception or its subclass instance to implement, so it is often called error handling as exception handling. On the syntax and inheritance structure, if a method declaration throws an instance of Throwable or subclasses, as long as it is not an instance of error, java.lang.RuntimeException, or its subclass, you must explicitly use the try, catch syntax to handle it. Or declare this method with throws to throw an exception, or the compilation will fail. The purpose of the exception being examined is that when the API designer implements a method, some conditions can cause an error, and the client that invokes the method has the ability to handle the error, requiring the compiler to remind the client that it must explicitly handle the error, otherwise it cannot compile and the API client does not have the option to process it. A class instance derived from RuntimeException, which, on behalf of the API designer, throws an error when certain conditions are true, and that the API client should be checked before calling the method to avoid an error, named execution-time exception, Because the compiler does not force it to be handled syntactically, it is also known as a non-inspected exception. In addition, if the parent exception object is caught before the subclass exception object, the chunk of the catch subclass exception object will alwaysWill not be executed, the compiler will check for this error. To complete the program compilation, you must change the order in which the exception objects are snapped. When the chunk contents after the catch exception are duplicated, multiple snaps can be used starting with JDK7, with the premise that the contents of the chunk must be the same, but still the exception is inherited, the exception listed in the catch brackets must not have an inheritance relationship, or an error occurs.
3. To catch or to throw
If an exception occurs in the method design process, and you do not have enough information at design time to know what to do (for example, you do not know what the link library will be used for), you can throw an exception and let the client that invokes the method handle it. If a checked exception is thrown during the operation of the object, but the current environment information is not sufficient to handle the exception, you cannot use try, catch processing, which can be handled by the client of the method based on the environment information that was invoked at that time. To tell the compiler the truth, you must use throws to declare the exception type or parent type that this method throws, and compile to pass. Throwing a inspected exception indicates that you think the client that called the method is capable and should handle the exception. If you think that the timing of the client calling method throws an error, and you want the client to prepare a precondition before calling the method, you can throw a non-inspected exception to let the client know about the situation. , if the exception is a non-subject, the compiler does not explicitly require a try, catch, or use the throws declaration on the method, because Java is designed to assume that a non-inspected exception is a vulnerability caused by improper program design, the exception should be automatically spread out, should not use try, catch to attempt processing. In fact, when an exception occurs, you can use try, catch to handle exception handling that the environment can do at that time, when the environment cannot decide what to do with the part that can be thrown by the client that invokes the method. After a partial error is processed in the catch block, you can use throw (note not throws) to throw the exception again. You can throw an exception in any process, not necessarily in a catch block. If you use inheritance, a method of a parent class declares throws some exceptions, and subclasses redefine the method by: 1. Do not declare any exceptions to throws. 2.throws some exceptions declared in this method by the parent class. 3.throws Parent Class The subclass of the method in which the exception is declared. 4.throws other exceptions not declared in the parent class method. 5.throws the parent class that declares the exception in the parent class method.
4. Intimate or cause trouble
Java is the only language that uses exceptions. There are two purposes: the first is documentation, the exception declaration will be part of the API operation interface, the client as long as the lookup file, you can know the method may throw some exceptions. The second is to provide compiler information, so that the compiler can check out the API client at compile time to not handle the exception. The exception is well-intentioned and helps the program designer to notice the likelihood of the exception and handle it, but when the application is scaled up, it becomes increasingly difficult to maintain, not necessarily when you customize the API, or by introducing an API that throws a client exception at the bottom. When a sqlexception occurs, the best way is to bring the exception to the user screen, such as Web technology, to display the error message on the page to the manager. As the application evolves, exceptions can also be considered for evolution, and perhaps initially designed to be subject to an exception, but because of a number of factors, it is also necessary to evolve the inspected exception into a non-inspected exception.
5. Understanding Stack Traces
In the case of multiple method calls, the point of the exception may be in a method, if you want to know the origin of the exception, and the stack propagation of the exception under the multiple method invocation, you can use the stack trace to obtain the relevant information. The use method is to call the Printstacktrace () of the exception object directly. The stack trace information shows the exception type, the topmost is the source of the exception, the following is the order of the calling method, the program code line is corresponding to the original program source code, if you want to get the individual stack trace elements for processing, you can use Getstacktrace (), Without doing anything after catching an exception or doing inappropriate processing, this code can cause serious damage to application maintenance. When using throws to re-throw an exception, the exception's trace stack start point is still the source of the exception, not the place where the exception was thrown. If you want to make the exception stack start to throw out the exception, you can use the Fillinstacktrace () method, which reloads the exception stack, sets the starting point to the place where the exception is thrown, and returns the Throwable object.
6. About Assert
The execution of a program at a certain point in time or under certain circumstances, must be in or not in a certain state, if not, it is a serious error! After JDK1.4, the assertion function keyword is assert, in order to avoid JDK1.3 or earlier versions of the program using assert as a variable to cause a name conflict problem, the default execution, do not start the assertion check, if you want to start the assertion check at execution, you can specify when executing Java instructions- Enableassertions or-ea independent variables. The assertion is that an execution point in the decision program must be or is not a state, so it cannot be used as a judgment like if, and assert should not be part of the program execution process.
Second, exception and resource management
1. Use finally
If you create a FileInputStream instance, the document will be opened, and close () should be called when not in use. If you want to be in any case, finally must perform the close action, the try, catch syntax can also be used with the finally, regardless of whether there is an exception in the try block, if the write finally block, then the finally block must be executed. If the process in which the program is written returns first, and there are finally chunks, then the finally chunk is executed before the value is returned.
2. Automatically try to close the resource
As shown in the 249-page code of the book, the object that you want to try to automatically close the resource is written in parentheses after the try, and if no catch is required to handle any exceptions, you can not write or write finally and try to close the resource yourself. Of course, you can also match catch (book 250) with automatic attempt to close resource syntax. When you use an automatic attempt to close resource syntax, it does not affect your handling of specific exceptions, and in fact, the automatic attempt to close resource syntax is simply to assist you in shutting down resources, rather than handling exceptions. Do not attempt to write your own program code to close resources, which will cause duplication!!!
3.java.lang.autocloseable interface
JDK7 tries to close the resource syntax of the applied object and must operate the Java.lang.AutoCloseable interface! Autocloseable is a new interface for JDK7, and only the close () method is defined. As long as the Autocloseable interface is manipulated, it can be applied to attempt to close resource syntax. Attempting to close resource syntax can also close more than two object resources at the same time, as long as the middle is separated by semicolons. It is worth noting that in the parentheses of the try, the sooner the object resource is written, the sooner it is closed!
Nineth Chapter
I. Collection of objects using collection
1. Understanding the Collection architecture
There is often a need to collect objects in the program, so far, you've learned that the way you can collect objects is to use an object array, and in javase you actually provide several classes of objects to collect. Instead of re-creating similar APIs, you can take these classes directly. The behavior of the collection object, like the Add () method of the new object, removes the object's remove () method, and so on, is defined in java.util.Collection. Since the object can be collected, you can also get the object, this is the behavior defined by java.lang.Iterable, it defines the iterator () method to return the Java.util.Iterator operand, you can get the object. However, the collection object will have different requirements, if you want to record the index order of each object at the time of collection, and can retrieve the object by index, such behavior is defined in the Java.util.List interface. If you want to collect objects that are not duplicated and have the behavior of the collection, it is defined by Java.util.Set. If you want to collect objects, arrange them in a queue. The collected objects are added to the tail end, and when the object is obtained from the front end, Java.util.Queue can be used. You can use Java.util.Deque if you want to add, remove, and move the ends of a queue.
2. List with index
A list is a collection that collects objects and preserves the order of collected objects in an indexed manner, with one of the operations classes being java.util.ArrayList. When viewing the API file, it is found that the list interface defines many methods for indexing operations, such as Add (), remove (), set (), and so on. Java.util.LinkedList also operates the list interface, you can change the book on the 264-page example of the ArrayList to LinkedList, and the results are unchanged, then when to use ArrayList, when using LinkedList it? In short, ArrayList is suitable for sorting and can get better speed performance. The LinkedList uses a link structure, which is more appropriate when the index order needs to be adjusted.
3. Content-not-duplicated set
The same is the collection of objects, in the collection process if there is the same object, it is not repeated collection, if there is such a requirement, you can use the set interface Operation object, String's split () method, you can specify how to cut the string. Hashcode () is generally used to determine whether an object is the same as equals ().
4. Queue that supports queued operations
The queue inherits from collection, so it also has the collection add (), remove (), Element () methods, but the queue defines its own offer (), poll (), and Peek (). The main difference is that when a method such as add (), remove (), element () fails, an exception is thrown, and a specific value is returned when a method operation such as offer (), poll (), Peek () fails. Similarly, methods such as AddFirst (), Removefirst (), GetFirst (), AddLast (), Removelast (), getlast () are defined in deque, and exceptions are thrown when the operation fails, while Offerfirst (), Pollfirst (), Peekfirst (), Offerlast (), Polllast (), Peeklast (), and so on, will return a specific value if the operation fails. Also, remember that the stack structure is advanced after out!
5. Using generics
When you use collection to collect objects, because you do not know the shape of the collected objects in advance, internal operations use object to refer to the objects that are collected, and the objects are returned as object types when they are retrieved. So if you want to operate on a class-defined behavior, you must tell the compiler to re-play that type. The generic syntax is added after JDK5. If the interface supports generics, it is also convenient to operate, as long as the declaration reference when there is a specified type, then the creation of the object will not have to write the type, generics can be defined only on the method, the most common is the static method to define generics.
6. Introduction to lambda expressions
As in the 279-page example of the book, you will see that the information is repeated, that the request variable has been told to be the request type, and that the anonymous class syntax for the request instance has been written again, in fact the request interface has only one method that must be implemented, when this happens, You can use lambda to simplify your programs in JDK8, and the syntax for lambda expressions omits interface types and method names. The left is the parameter column, and the right is the method body. The compiler can learn the syntax omitted information from the declaration of the request request. Although it is discouraged to use lambda expressions to write complex calculations, if the process is more complex and cannot be completed in a single line of lambda expressions, you can use the chunk {} notation to include the calculation flow. If the method must return a value, you must use return in the chunk.
7.Interable and iterator
In fact, either list, set or queue, there will be a iterator () method, which is defined in the collection interface before JDK5 appears, and the list, set, and queue inherit from collection, So also have iterator () behavior. Iterator () returns the operand of the Java.util.Iterator interface, which includes all objects collected by collection, and you can use iterator's hasnext () to see if there is a next object, and if so, use next () to get the next object, so You can use foreach () to display the collected objects regardless of list, Set, queue, or any collection. After JDK5, there is an enhanced for loop, which is seen in the array, in fact, the enhanced for loop can also be applied on the object that operates the Iterable interface. JDK8 before the interface once new syntax, all the implementation of the interface classes have to operate the method, the existing various APIs to implement the Iterable interface is too many classes, so that these classes do not have to operate foreach () and on the JDK8 compile error? No! Because JDK8 evolved the interface syntax. Allows the interface to define the default method.
8.Comparable and Comparator
After the objects are collected, it is often an action to sort the objects, but instead of having to do it yourself, Java.util.Collection provides the sort () method, and the collection sort () method accepts the list operand because it has to be indexed for sorting. The collection sort () method requires that the ordered object must operate the Java.lang.Comparable interface! The collection sort () method takes a object as a comparable when it compares a object with a B object. Then call A.compareto (b), if the A object is less than the B object in order, returns a value less than 0, or 0 if the order is equal, and returns a value greater than 0 if the order of a is greater than B. Check the API file that the integer has an interface for manipulating comparable. The collections sort () method has another overloaded version that accepts the operands of the Java.util.Comparator interface, and if this version is used, the order is determined by the compare () definition of comparator. In the Java specification, the order-related behavior, usually either the object itself is comparable, or the comparator object is otherwise specified to tell how to sort. One of the operations classes of set Java.util.TreeSet not only has the ability to collect objects that are not duplicates, but also sorts the collected objects using the red-black tree, provided that the object being collected must be comparable or the comparator object is specified when the TreeSet is created. One of the operations classes of the queue Java.util.PriorityQueue also, the objects collected to Priorityqueue will determine the order of the objects in the queue according to the priority you specify, the notification of priority, or the object must be comparable, or the creation of PRIORITYQ Specifies the comparator object when Ueue.
Second, the map of the corresponding key value
1. Common Map Operation class
Before using the map-related APIs, it is helpful to understand the map design architecture before you use the API correctly. The commonly used map operation classes are JAVA.UTIL.HASHMAP and Java.util.TreeMap, which inherit from the abstract class Java.util.AbstractMap. When you create a map operand, you can use the generic syntax to specify the type of the key and value. To establish a key value corresponding, you can use the put () method, the first argument is the key, the second argument is the value, for the map, the key is not repeated, the key is determined whether the repetition is based on hashcode () and Equals (), So the object as a key must manipulate hashcode () with Equals (). To specify the key to retrieve the corresponding value, the Get () method is used, and the key is unordered when the key value is established in HashMap, which can be seen in the execution result. If you want the key to be ordered, you can use TreeMap. If you use TreeMap to establish a key value corresponding, the part of the key will be sorted, provided that the object acting as the key must manipulate the comparable interface, or the object that specifies the comparator interface of the operation when the TREEMAP is established. The general properties of SetProperty () specify the key value of the string type, GetProperty the key of the specified string type, and retrieve the value of the string type, often referred to as the property name and property value: Properties = Left Set property name, The property value is set on the right. You can use the properties's load () method to specify an instance of InputStream.
2. Access Map key values
Although map has no inheritance relationship with collection, they are each other's APIs. If you want to get all the keys in the map, you can call map keyset () to return the set object, because the key is not duplicated, so it is a matter of course to return with the set operation. If you want to get all the values in the map, you can use values () to return the collection object. The author has been emphasizing the importance of the object-oriented foundation and understanding the API architecture, in the face of a large API, only a solid object-oriented foundation and understanding of the API architecture, can be simplified to use api! Map does not inherit iterable, there is a foreach () method that is defined on the map interface, which can be combined with a lambda expression to get a good readability when iterating over keys and values!