20145326 Java Programming 5th Week of study summary

Source: Internet
Author: User
Tags comparable finally block iterable stack trace

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!

Problems in teaching materials learning and the solving process

Actually feel good, like Lou Teacher said, the No. 4567 chapter of the content is the Java core content, more abstract difficult to understand. After the content is to introduce the application of various APIs, are living examples, more specific, if it is difficult because of this part of the knowledge is unfamiliar, not familiar. You first clear the clue, and then read a few times more books, more than a few times to knock code. It feels like it's coming up! Should pay attention to the scientific study method ~ Not blind!

Problems in code debugging and the resolution process

I'm curious. is the code in the finally block bound to be executed? To verify that the code in the finally block is bound to be executed, my idea is to add some terminating type code before the finally block to see if it can be prevented from executing.

The output results are as follows:

Add return to this code snippet:

At present, the finally block should be executed. But my classmates told me that there is a situation where the finally block is not executed, that is, add system.exit (), the meaning of this code is to terminate the JVM.

Other (sentiment, thinking, etc., optional)

This week is self-taught two chapters, have to admit that from the fifth week began a little tired. Last week, a classmate in their own blog to give Lou teacher comments, said that the amount of study is too large, no efficiency. Lou Teacher explained that the reason for this experience, it is because did not find a suitable for their own good learning Method! Before I wrote this blog, I kept thinking back to what Lou's teacher said in class. To learn to grasp the focus, the strength of the blade, to find fun, maintain passion, improve learning efficiency! Lou teacher said last week, learned 4567 chapters, in fact, the core knowledge of Java is also finished, followed by some of the application of the class. So I went to see the textbook with the purpose, not blind. I later found this particularly important! I know the eighth and Nineth chapters are about the application of some classes, so I read a book, while summing up, read a total of how many APIs, each API architecture is what, each API's role and considerations are what. In this way there is a systematic look at the textbook, the sense of efficiency is very high! And the mind is clear. In fact, this knowledge is not difficult, we just feel strange. Students have fear mood and weariness, of course not to go in, but also talk about what efficiency! The knowledge of the eighth and Nineth chapters is not as abstract and difficult to understand as the previous objects, encapsulation, inheritance of those basic concepts, are living concrete examples, the acceptance is actually quite fast. I looked at the system, the feeling has mastered the 70% bar ~ So Lou Teacher said is right, the important thing is not to learn how much Java knowledge, but through continuous learning process, to summarize a set of suitable for their own good learning methods, which will be useful life. Of course, different people are certain that the situation is not the same, suitable for their own is the best. My biggest harvest this week is to really realize that learning should also speak science, not blind. Time is used much, not necessarily to learn well. Find your own learning methods to improve efficiency! This is more important than everything! Adjust your own mentality, any thing do not have fear mood, everything beginning difficult, as long as is right, insist! Will certainly benefit from the end!!!

Learning progress Bar
Lines of code (new/cumulative) Blog volume (Add/accumulate) Learning time (new/cumulative) Important growth
Goal 3500 rows 20 articles 300 hours
First week 120/120 1/1 14/14
Second week 340/460 1/2 14/28
Third week 200/660 1/3 14/42
Week Four 320/980 1/4 14/56
Week Five 280/1260 1/5 14/70

20145326 Java Programming 5th Week of study summary

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.