A year of handmade Java old A book started pre-sale

Source: Internet
Author: User
Tags what magic

Java old A This book for a long time, yesterday finally began to china-pub on the pre-sale, other sites may be slower, but since the call presale, it must have not arrived.

Interested people can go to see Kazakhstan (subsequent other website addresses will also be published here):


For the contents of this book, please refer to: http://blog.csdn.net/xieyuooo/article/details/38373409

It has all the catalogue information, cover, etc. of the book.

The original purpose and history of writing this book can be see:



In the early period, the manuscript sample is affixed to a section to the blog, which can be consulted:


Start Presale, I by the way Preface, the first chapter part of the content, the preface is written to the reader friend, we can refer to whether the book is suitable for their own, as follows:

The book is titled "Java Commando", also known as "Java old a", the purpose is very simple, hope as a reader friend of you, one day can become a single-man combat ability extremely strong Java programmer. As we all know, Java programmers abound, I hope to learn this book readers a willing heart, outstanding, to acquire a good ability to become the special forces of the Java community.

About the book

Rome, Cold day, this book is not what magic cheats, so it can not let you in a short period of time from a bird into a cow, but also can not let you from the cattle to become a master, this book is to hope that readers can be entangled in the time to think of it can also rely on it. Because this book is not only about some knowledge, but also contains the author and colleagues of the work experience, as well as the work experience of the pain and struggle, we hope that in the company of this book, you in the struggle to choose not to abandon the ego, but to persist to the moment of victory.

The author himself is not a bull, more than a brilliant master, can only say that some of the things we experience may be worth sharing, these content not only contains some knowledge, but also contains a lot of ideas, methods and attitude to face problems, pay attention to the improvement of foundation and cultivation. If one day you find this book to bring you More is the method, so that you build up your own many ideas of rapid learning and growth, then the book of an important purpose is achieved; if one day you find that some "bull cheats" will be easier and more enjoyable than before, then perhaps this book a little credit.

This book is not a lot of code, nor is it dedicated to some of the specific knowledge section of the book (such as the JVM), and will not be specific to the knowledge of the section to do a detailed description, nor to explain the details of the API, more will not fully explain their source code, this is meaningless. Through this book, I hope you can learn from the heart of "knowledge is boundless", we always meet the problems we have not seen, need to learn is how to face these problems, that is, how to think and positioning, how to learn and grow.

In this book, there may be a variety of "transposition thinking" approach to explore some of the technical content, from the perspective of technology itself, focusing on the various mysteries contained in the technology and explore some of the mysteries of ideas, rather than explain the use of some technology, I hope readers in the process began to consciously understand the depth of knowledge should be , and at the same time really grasp the Java Foundation, improve self-knowledge, but also find ways to improve the foundation.

Many of the dialogues and discussion patterns in this book are suitable for meditation like fiction, and I believe that if you can meditate, you will benefit from this book, whether you are a beginner or a person with a certain foundation. When I first entered university, I was a person who didn't know anything about computers, and had the experience of memorizing code to pass the C language exam, and then, through constant efforts, I was able to write the book. Therefore, this book will be combined with Fat elder brother from a computer in the process of "illiteracy" began to grow up in some of the "lovely" thought experience, if you have a similar thought experience, hope that this book can help you, but also hope you understand: As long as you want, you will be OK!

Some of the content style of the book will be biased to entertainment, the content described by the technology will not be so rigorous, due to the lack of rigor, may allow different readers to create the situation of the beholder, benevolent see. For some people who have the same work experience, there may be a heartfelt resonance, for beginners can be an approximate image of understanding. While many of the explanations in the book are not technically accurate, I do not want the beginner's "little Friends" to focus solely on the topic of entertainment itself, but to think about some of the perceptual knowledge that this example of entertainment brings to them.

This book will talk about some of the growth of the content, so we can first about the different levels of how people would think, how to do things, so that everyone has an image of the understanding.

Java Learning three-Duan

Many beginners, like the headless flies, all around, all want to learn, learn to lose, and like a dead end, not even the habit of independent thinking, encounter problems to ask, and then solve the problem. They often ask, "Why are my things so good in here and not useful in that?" "Because you still do not know the cause of the problem, of course, do not know so many why, any problem needs to locate the analysis, then solve, and then summarize." Face the problem to calm down to the basis of their own understanding to analyze the possible causes, and then gradually narrow the scope, and then locate the problem. If a mistake is made to know the reason, then the direct design of a machine to answer the question, without the need for any human intervention.

A certain degree of people, know how to think, know how to think, can solve most of the practical problems, they can not only start their own positioning problems, but also began to be "forward-looking", thinking about some of the potential problems in the future, but also began to gradually focus on some of the intrinsic principles. However, it may be bold, these people may make some mistakes that should not be made, they are usually some very good programmers, often in order to demonstrate their technical ability, will be not worth doing things constantly refinement and optimization, or to do something others have done, If the main business is lost because of this, it is often said that it is over-optimized, over-engineered, and repetitive manufacturing. The author himself has the same personal experience, and very contradictory is whether it is really over-design, in different scenarios will have different views and evaluation, so this stage of the students, usually have a tangled period. At this stage people began to pay attention to internal and external double repair, also is a product Tuchen, stagnant water chenyuan process, because there is a certain foundation, learning a lot of knowledge is very fast, in the knowledge will have a great breakthrough, will be gradually deepened in the intellectual point, may be in the work whether business or technology have a lot of choices, He is considered to be a man of great ability in work. Some very "bull" developers will start to realize how much code to write will be more elegant and efficient, with simpler code to solve more problems, but not yet up to the system level and architecture level.

Perhaps a higher level of people began to have a strong global view, so that the overall system is more maintainable and scalable, the system has good performance, stability, and can deal with all kinds of architecture, deployment, standardization and other related issues, in some areas is also a very important person to speak. They may spend a lot of time writing general-purpose models and designs, simplifying the puzzle and solving problems that no one can solve. Usually try to make the system maintenance into a configuration or a few simple code, but can top up a group of people to write a bunch of code, this is the Special Forces Programmer's "fast", "quasi", "ruthless", "stable".

The various levels here are simply the author "talking to himself", does not mean anything, to achieve a level in the heart can really let themselves grow rapidly. In addition, look at these levels does not mean that I am a beginner today, tomorrow will be bad habits to change after the "reborn", also does not mean that they have a little thing in the style of the master on behalf of himself is a master. These things are going through some things to form some natural consciousness, we just consciously to learn why they do things, why young people are more active than the old employees, but generally speaking, "Ginger is still old spicy."

Reader object of the book

-Suitable for objects

(1) People who have a certain Java foundation and want to grow in Java technology.

The book learning has a certain threshold, if it is a beginner, you can start with some examples in the book to guide, hoping to understand why, and then look at the explanation.

(2) For beginners who can meditate on a book, they can read it iteratively.

Although there is a certain threshold, but beginners as long as the meditation, iterative reading several times, you may also be able to understand that there are many ideas, methods, solutions to problems, look at the side of the problem, and even face the problem of the mentality, then can also benefit a lot.

(3) This book is a carrier, a respected self-cultivation, internal and external double repair carrier, practice to see individuals, so suitable for the purpose of self-promotion as the main goal of the reader.

(4) Work for a period of time, the direction of knowledge and development is very confused, even some ideas are more confused, but also eager to solve these problems, eager to grow their own, eager to find their way to the people.

-Not suitable for objects

(1) Java Master and cattle, because this book does not help you from the cattle to become a master.

(2) Do the client (such as Android) or embedded Java programmer, because most of the content in the book is server-side Java to explain, very little consideration of the client's problems.

(3) If you are desperate for yourself or everything around you, everything you see is evil, hypocritical, and you don't want to make progress.

(4) I hope this book is a technical dictionary of the students are not suitable for reading, because this book is not a code encyclopedia, nor is the aggregation of accurate knowledge points, not the list of APIs.

(5) Students wishing to systematically study certain professional knowledge are not suitable for reading this book because this book is about a "fragmented" approach to learning, or a way of dealing with problems on the basis of small examples.

How to read this book

As the author of the book, I hope that the reader can happily learn the knowledge, every day free time to look at rather than a pressure, the face of technology has the ability to think alone, rather than mastering a certain technology itself, through the easy access to a lot of knowledge and can have experience, continue to summarize, abstract, can draw their own analysis problems, Solve the problem of the method, honed beyond the common Programmer's foundation, eventually become Java old A.

This book is actually a Java book, talk about, will try to use easy-to-understand ways to explain some of the complex problems and techniques. However, after all, this is not a book of entertainment, some content fat brother will still say more rigorous. In addition to explaining some of the "skills" of the technology, most of the technology will not speak too deep, mostly just to give you a thought, when you need to contact the deeper technology, in this book may have a more image of the example for your reference, maybe you know how to understand. If the foundation is good enough, you will find original aim, everything can be attributed to the foundation, and most of the complex ideas are derived from the inspiration of life.

If it is a beginner, I hope you do not expect to see too much content every day, but hope you look at it as far as possible to think, not fully understand, every day can have a experience, when you encounter some problems in practice when you start to have inspiration, this book may prove it all.

The technology mentioned in this book is just a guide, a discussion, a way of thinking, when it comes to explaining a good or bad situation, it is common to look at different aspects of the problem in a variety of ways, and then explain why there are such experiences, and may also explore whether these experiences can be useful for life. Because the technology of the times in the constant revolution, the current technology is very rampant, but all the same, we have to keep up with the times and summed up, perhaps many times we do not have the energy to learn all the knowledge, but have the energy to improve their learning ability to learn more things, but also have the energy to explore the knowledge in the field of work, The premise is that there should be a habit of exploring mysteries and enough foundation.

The purpose of this book is personal growth, very little talk about teamwork and standardization of knowledge, of course, as a man fighting ability is very strong, should have this awareness and thinking, even if not mentioned in this book, we should also grasp. At the same time, readers are invited to pay attention to the book advocated by the individual combat capability, not to expect everyone to do a technical loneliness, but better to work.


-This book will use HOTSPOTVM 1.6 as an example (the JVM version can be obtained by the command "java–version"), and the test example is described separately if it is tested in a specific OS environment. The contents of JDK 1.7 are also mentioned in the book, and the corresponding code should be selected for JDK 1.7 if it is to be run.

-In this book "Some examples", you must use the-server mode to run and simulate, especially in the 5th chapter of concurrent Programming in many examples, in the example is usually a special note and description, please pay attention to the reader.

-Space limitations, the examples in this book are mostly just fragments, to illustrate the actual problem-oriented, need a complete example, please refer to the relevant demo information in the book CD, the examples in the book have the actual code corresponding to it, in addition to very complex code, from the demo to get the code from the relevant configuration, Can be run directly on the corresponding platform according to the specified results.

-The code of this book is divided into two sources, source code for the third-party source, can be downloaded to the official website see, the book will introduce the source of the version and ideas, and posted some of the key source of function and design ideas.

-The book begins with the 2nd and each one has a "to-do", which is intended to give the reader a better idea of what the point of the content should be, what it will say, what it will bring to you, and why you need it.

-The internet is called the author "fat Brother" or "fat elder brother", so in this book, will also use these two titles as the author's pronoun.

Content Introduction

The book sub-book, a total of 5, the volume of two content is the foundation and source text, emphasizing the promotion of personal improvement, but also the main thrust of the book, I hope to help readers to enhance the "skill" of the reader, the next book, the contents of the book into the design, implementation of the details.

The book

The 1th chapter of Java Foundation

Suggest that all readers of this book read the contents of this article, the so-called "martial arts do not practice, to the old one empty", whether you want to become an old Class A programmer, the foundation of the promotion is very important, through the 1th article of learning, I hope readers can know how to verify their own foundation, how to improve their skills, and how much You have to rely on your own property!

The 1th chapter from a simple point of view to verify the foundation, through a few simple examples to illustrate how we should master the foundation of Java, but also contains an "old Class A programmer" in addition to the foundation of the mentality of facing adversity.

Chapters 2nd and 3rd describe the basics of how computers work and the Java virtual machines. Fat elder brother thinks a good Java programmer, should know how the program is running inside the computer, need to know how the virtual machine is running, efficiency contrast how, this is like "martial arts person, need to know what is military study".

The 4th chapter explains the Java communication, after understanding the basic operating principles, you should understand that many network interactions have been wrapped in the Java framework is no longer like the communication program, like the "renovated house, you no longer know what the house is built with what." But if you are old A, you should know this, so you can know how to solve all kinds of strange problems, you will find: "All from the foundation, accidental problems hidden inevitable."

The 5th chapter explains Java concurrency, if the reader friends do not meet, you can skip, but to become Java's old A, this should be considered the basic knowledge, old A should know how Java concurrency. In addition to the client program and microcontroller, Java Concurrency Program processing in fact everywhere, like "a city of traffic, a lot of vehicles need to communicate, how to improve traffic, avoid traffic accidents."

The 6th chapter explains the database knowledge, most programmers should use the database, the file, through the 4th chapter of the communication content, there should be some concepts, but in the face of storage, you want to understand some of the inside, understand what a programmer needs to know inside, this may make your work more handy. Having said so much, have you found out why you learn so much about Java? Yes, you need to know that "a lot of military study, in the face of different ideas collide to learn, will have more experience." As an old A, will have a man-in-the-battle ability of a very strong combat quality.

The 2nd chapter of source code

Programmers who reach a certain level will generally start to be interested in the implementation itself, wondering why, and understanding how others are designed and implemented.

Initially in the face of the framework, it may be to guess or test how it is implemented, but gradually found that guessing and testing is not so reliable, because the version and environmental factors are too large, we began to want to know something inside, see the source becomes a necessity. There is no secret in front of the source code, read the source code, you will be able to locate and write the problem of self-confidence, began to have a quantitative understanding of the technology itself.

This article is not the network of the World source code, and will not do a full explanation of a provenance, but by reading the source to explain how we should read the source code.

At the beginning of this article will first explain why to read the source code, explain what source, how to read the source code, please have a question of small partners to pay attention to OH.

The 7th chapter explains the basic principles of Java Common framework, including: Reflection, AOP, ORM, annotation and configuration file. Not only does this explain the technology itself, but it also links to some possible implementations of the actual framework. Old a must: "Know it, know its why."

The 8th and 9th chapters explain the source code of JDBC and spring respectively, and this will not explain all the source code and key points of these three-party packages. But through several different types of framework source code, I hope readers can understand the source of the "way of thinking, design, architecture", and understand the different source of the difference. Although the difference is many, but if you have some "hundred chuan Panerai, originates from the same" the feeling, then the small partners grew a lot.

The 10th chapter is the knowledge summary of the 2nd article, after reading the source code is not finished after reading, but should have some experience. Through the basic knowledge of the source code and some of the reading of the source code, we gradually have the ability to contact a frame we have never seen, we can probably know its approximate internal, and most of the time can easily handle it, even if there is a certain difficulty will be viewed from the fundamental point of view of these technical issues, Get to know the inside by looking at its code more quickly, without being fooled by the use of floating surfaces. This is like although the Magician's performance dazzling, but in their eyes are known to the bottom of the root, because we are also professional, so should not be confused by something.

Next book

3rd Chapter Design

Old A, although not as a strategist: "In the plan, winning thousands", but also need to have a global deployment of ideas, on-the-spot strain and retreat plans and routes to have a global control, can "take the admiral in hosts", the use of the lowest sacrifice to achieve the highest results.

In the design, fat Brother hopes to bring you not only the existing old a technology, but also contains many of their ideas. Since it is thought, nature is the best combination of the scene, it needs to be integrated into the wisdom of old A, not limited to the form of expression, because these forms are only a carrier of the idea of transmission.

In the 1th chapter, Fat elder brother will use the example of the usual work to illustrate some common design patterns, but will not be all the Java design patterns in full detail, because this is not the main theme of the book, and that does not make much sense. In the practical application, the scene is very important, the change is far more than the "moves" provided by these design patterns themselves. The pattern itself provides a suggested design approach, like Kong Cong's "Moves are dead, people are alive", the same military study at different ages, with different opponents, whether it is the order of moves or the action of the spot will have a great change. If in combat duel repeatedly with the pattern to contest, will be the routine traction, will be the opponent to disrupt the rhythm, and the routine itself to provide us with a way to deal with the scene, flexible application can be used in combat, so as to achieve "No recruit wins there is a recruit" realm.

The 2nd and 3rd chapters introduce the design of two examples, which are two completely different types of programs that try to apply some of the knowledge and ideas of design patterns in this process, that is, the need to know how to use the moves to the enemy. But let's not just confine ourselves to the examples given in these two chapters, because the actual scene can be changeable, and the scene that you encounter needs to be figured out and thought over. Our example is usually not written to the implementation part, to the end of the design part, and I hope you can understand that "thought and method should originate from life and nature".

The 4th chapter realizes the article

In the original plan, fat brother did not intend to write about the "implementation" aspects, but fat brother found in the actual work, small white "children's shoes" is likely to face the most is to achieve, so added this part of the content. But in the implementation of the article is not to take a business instance to write code, what to talk about it?

The 4th chapter is about the interaction, development mode, mentality, technical thinking and some optimization ideas of various working people in the project. The 5th chapter, simply talk about some of the use of the UI, complex points there. The 6th chapter, talk about the actual work often encounter "pit", these pits are not easy to be found, but we often easy to fall into, I hope you know not only these pits, but through these pits to understand that many technologies are a "double-edged sword, there are advantages will be bad", only the best scene to choose the most appropriate technology, Learn how to quantify and choose, at the same time need to understand that the current work on the quality of personal requirements are increasingly high.

The 5th chapter of the Theory of extension

Extended chapter for the talk, but also on the Tao, the reader can first read the 5th chapter of the content, this is an extension of knowledge and ideas. An old A, should know some of the industry's technology, so-called: "Know the Enemy, victorious", contact any kind of problem, must have the corresponding solution.

The 7th and 8th chapters introduce some cluster knowledge and distributed knowledge in a cursory way (but it does not mean that the actual technology is as simple as a quick walkthrough). As an old a programmer, fat man thinks he needs to know this so that he can do something better, or have a chance to do something more challenging. You may not be able to use this today, but you will be more handy when you use it.

The 9th chapter explains some things about the quantification and trade-offs of technology, and talks about time management, teamwork, over-optimization, anticipating problems, and realizing ideas of different projects. The central idea here is that we should consider various cost and value issues on the path of technological pursuits, starting with individuals and looking at teamwork.

The 10th chapter is the end chapter, mainly to explore some mentality and inspirational, interested in small partners can see, no interest in this chapter without concern. Modern old A, in addition to excellent quality, but also to have wisdom, wisdom contains a wealth of knowledge, at the same time contains the understanding of the world, meditation do a good job now, have the opportunity to do a good job in the crowd among the crowd stand out.

The above section is the main part of the preface, the following paste a little bit of the first chapter of the small content, we can refer to whether it is suitable for their own tastes:

1.1 String example, witness our foundation

Wow, the 1th section begins to tell the code example, can't stand it, fat brother, you are dead! All the books in the 1th verse are written in this field.

Haha, chubby elder brother is born to be a counter-heaven person Oh, hope you can first practice has the perceptual knowledge, then carries on the theory understanding inside.

The following code is adapted to a section of the network of cattle people, first look at code listing 1-1.

Code listing 1-1 A section of a string comparison program

private static void test1 () {

String a = "a" + "B" +1;

String B = "AB1";

System. out. println (A = = B);


Fat brother, do you test my IQ? We usually compare two objects not with equals ()? The teacher told me: two strings with an equal sign is not matched, the result should be false. So how much is the result?

Operation Result:


What the? Is it true? Why is true? Is this going to reverse the day? This little program completely overturned my experience and the truth that my teacher taught me! "My little friends and I were stunned ..."

Fat elder brother Tell you this can not blame teacher, teacher with door, practice rely on individual !

Maybe a friend has made a true or guessed true, then can you know why? If you know, then this section skips, no longer look, if you do not know, listen to fat brother to tell you what he understood.

What do you need to know to understand the problem?

What do you do about "= ="?

What about equals?

What is a and B in memory?

Compile-time optimization scenarios.

The following will be a lot of things, now we can stand up for a simple exercise, end a cup of coffee, slowly read the following content.

?? 1.1.1 about "= ="

The first thing to know is "= =" is used to match the contents of the memory unit, is actually a number, the computer is only a number, and in the Java language, when the "= =" match, is actually compared to the contents of two memory units is the same.

If the primitive types are Byte, Boolean, short, char, int, long, float, double, they are directly compared to their values. It should be clear to everyone that there is no further detail here.

If it is a reference (Reference), the reference value is compared, and "referenced value" can be considered to be the logical address of the object. If the "= =" operation occurs with two references, the address values of the corresponding two objects are compared. In other words, if the two reference holds the same object, it returns true, otherwise false if the reference points to null, which is also a specified value given to it by a JVM.

understand the moral: we each got a company offer, now we look at the people who get the offer is the same company.

?? 1.1.2 about "Equals ()"

The Equals () method, first defined in the object class, is defined by the use of the "= =" Method (which you can refer to in the source code of the object class). That is, if you do not rewrite the Equals () method, and the corresponding class has not overridden the Equals () method in its parent class list, the default equals () operation is to compare the address of the object.

The Equals () method exists, it is hoped that the subclass to rewrite this method, to achieve the function of the contrast value, similar to the string itself implemented the Equals () method. Why do you have to do it yourself? Since two objects are compared by the key attribute values of the specific business, determine whether they are "consistent or similar" and return to True|false.

confuse 1:equals () is not the contrast value? Why is that similar?

Answer: One day encounter the strange Man "Snail Master" A, give the sword to several people, the hunter used it for hunting, the farmer used it to chop wood, the general used it defend, the knight uses it to do the righteousness, punish and vice, and so on.

For example, when comparing the drawing size of some projects, because of the size of the detail error, you can think that the width and height are close, you can return to true, not necessarily the exact match. In addition, the properties of the sheet paper, in addition to the length, width, also like the name, storage location, volume number and other properties, but we may only need to compare its length and width, in this range the rest of the properties will not be considered. In other words, whether the value of two objects is the same is determined by your business, not the Java language.

sentiment: adapt, let the standard become value, give you a kind of thought and standard, you can have different use, can't merely theorem, we want to solve the problem!

after confusing 2:equals () rewrite, will it generally override the Hashcode () method?

To illustrate this problem, we should first add some concepts.

What is hashcode in Java -The Hashcode () method provides an object's Hashcode value, which is provided as equals () in the object class, but it is a native (local) method. Its return value is the same as System.identityhashcode (object) by default. In general, this value is a part of the object's head bits a number, which has a certain identity object meaning exists, but is never equivalent to an address.

The role of hashcode-it is to produce a number that can identify an object, however complex an object can be identified by a number. Why do you need to use a number to identify an object? Because you want to use the object in the algorithm, if not, many algorithms have to assemble their own numbers, because the basis of the algorithm is built on the basis of the digital. So how is the object used in the algorithm?

For example, in HashMap, HashSet and other similar collection classes, if you use an object itself as a key, that is, based on this object to implement hash write and lookup, then how can the object itself achieve this? is based on such a number, only the number can really complete the calculation and comparison operation.

Hashcode can only be said to be an identity object, so in the hash algorithm it is possible to open the object relatively discrete, so that you can find the data by this key to quickly narrow the range of data. But can not say that the hashcode value must be unique, so in the hash algorithm to locate the specific list, you need to further cycle the linked list, and then by equals () to compare the value of key is the same. At this point hashcode () and Equals () seem to be "natural pairs". In other words, one exists for the algorithm to locate the data quickly, and one is to compare the real value.

Similar to Equasls (), the Hashcode () method can also be overridden, and the overridden method will determine its distribution in the hash-related data structure, so this return value is preferably a data that is capable of relatively discrete objects. If an extreme situation occurs where hashcode () always returns a value, then they will exist in the same linked list of HashMap, and will be slower than the list query itself.

In JDK 1.7, the hash-related collection class uses string as key, instead of using the Hashcode method, but with a Hash32 property, and the remaining types remain unchanged.

Another way of thinking, hashcode () and Equals () do not have to be forced together, if you do not need to use such an algorithm, it is not necessary to rewrite the corresponding method, it is entirely up to you to decide, there is no syntax to enforce the statute.

Moral: does the sword need a scabbard? Baby, do you need a treasure chest? Does the male have to need a female? Does the Earth need a moon?

Instead, does the tree need soil? Does life need food? Does the fish have to need water? Does the world need sunshine?

sentiment : All lies in the scene and the demand, very need, but also may in some circumstances give up.

Some people say: Compared to two objects are consistent, you can compare the hashcode value and then compare equals ().

This seems to sound reasonable, but Fat brother himself does not think so! Why is it? Fat brother thinks that the hashcode value is not in order to compare the consistency of two objects exist, it can be said that it is consistent with two objects "a little relationship is not."

If you want to compare two objects to whether they are the same object, you can simply compare them with "= =" instead of Hashcode (), since it is most reliable to compare the address values directly to indicate whether the two objects are the same object. In addition, the default Hashcode () method initiates a native call, and two objects each initiate a native call (the cost of the native call is also not small).

If you are not comparing addresses, but comparing values, you naturally need to compare some of the attributes in the object. In the case of a string object, if you call the Hashcode () method of a String object, it will at least traverse all char[] array-related elements on the 1th call to this method to calculate the Hashcode value (at least, It is because this string can be traversed multiple times if the Hashcode () method is called concurrently, and some additional operations are required during the traversal. If the two objects in the comparison get hashcode, the natural two string objects will traverse the char[] array one at a time, respectively.

Even if the hashcode is the same, it also proves that the two strings are the same (this hashcode is calculated based on the value of the char[] array, and the different strings can work out the same value). You also have to loop all the characters in two strings again to prove that two objects are the same. Actually traversing two char[] arrays is the worst case, and equals () may not be doing this (in detail in Figure 1-2 later).

In other words, if the object of the two other custom type (not a String object) is judged to be different from the hashcode, it cannot be said that their values are not the same (it is possible that equals () matches a composite value, and hashcode does not have a relationship), Or do you want to do equals () so that going around often complicates the simple question.

Equals () What to do in the internal how to do, want to optimize, can be like the JDK comes with many classes, the first comparison of some simple property values, and then compare the complex attribute values, or first compare the business of the fastest to distinguish the value of the object, and then compare the other values, or compare address, length and other processing methods, Eliminate those mismatches as soon as possible.

It is said that the hashcode () internal operation of the rewrite is indeed many times simpler than equals (), in fact, this action decision can also be placed in the Equals () method of the 1th step to complete, without external program attention.

Add: The Equals () method of string first compares the incoming object to the current this is not the same object. In the lookup process of the collection class such as HashMap, nor is it pure equals (), and the first two objects are not the same object.

Good tired, rest and rest! Left three laps, right three laps, again to see Fat elder brother for you to do interpretation!

what are the memory conditions of a and B?

Back to the example in code listing 1-1, where the equals sign shows A and b pointing to the same block of memory, as if two people were given an offer from the same company, what were they like? See Figure 1-1, "dead Enemy, again together!" ”

Figure 1-1 Two enemies get an offer from the same company

Why is a and B two references to the same space? Please look at the contents of 1.1.3, but in this section we first understand some of the JVM's "East", in the 3rd chapter will be more detailed introduction. Small partners do not worry, we take a step by step to learn.

?? 1.1.3 Compile-time optimization scheme

A reference is directly assigned, the B reference is assigned by "+", why does A and B two references point to the same memory unit? This is the "compile-time optimization" of the JVM. So magical! The little friends were stunned!

When the compiler compiles code: String a = "a" + "B" + 1, it is compiled as: Stringa = "AB1";.

Why? Because all are "constants", the compiler thinks that the 3 constant overlays will get a fixed value, which is optimized so that it does not need to be evaluated at run time.

wonder: Why does the compiler do this optimization?

moral:"little fat" said that my expense statement was written and stamped, "Xiao Ming" said that my also OK, then merge together to mail the expense list bar. "Small sharp" said my quick to write, but have not stamped, then you write well then say it.

implication: in order to improve overall efficiency and save resources, can do things ahead of time to do. Do we consider these when we design a platform or language for ourselves?

add: There are many similar optimizations in the compiler (described later), for example, when an int i = 3 * 4 + 120 appears in the program, it is not the value of I at the actual run time, but instead it becomes i= 132 at compile time.

error Prone: The JVM will only optimize the parts that it can help you optimize, and it is not optimized for all content. For example, taking the example of a string superimposed above, if there are "variables" in several string overlays, that is, at compile time, it is not certain what the specific value is, then the JVM will not do such a compile-time merge. And the JVM will do exactly what kind of optimization, do not do what kind of optimization, we need to continue to learn to do the job better.

the same proof: The "+" operation of string is not necessarily slower than stringbuilder.append (), and if it is a compile-time merge, it is faster because it is obtained directly at runtime and does not need to be calculated at all. Similarly, do not firmly believe what way fast, what way slow, must pay attention to the scene. And why, in many cases, StringBuilder. Append () faster than the "+" operation of string? In the following article, Fat Brother will continue to introduce the reasons.

====> the length of the space, just post these.

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.