Java Foundation Series -01-starting from ==/equals/hashcode

Source: Internet
Author: User

Objective

After graduating from the Java Development for 2 years, from the initial Java Web development, into the development of Hadoop big data trends, more and more found their Java Foundation, data structure, multithreading and so on, is so fragile! What is more important than the foundation, should calm down, to learn them, from this blog start ~


Topic One: = = and equals


Let's first look at the source code for the Equals method defined in the object class:


650) this.width=650; "src=" http://s3.51cto.com/wyfs02/M00/71/1B/wKioL1XGpUeBnt2JAAAzIok0Uuo792.jpg "title=" Sogou _ 2015-08-09_08-47-57.png "alt=" Wkiol1xgpuebnt2jaaaziok0uuo792.jpg "/>


In the object class, Equals is the use of = = To achieve comparisons between objects.


We know that for basic data types, = = compares their values for equality, so what is the comparison of = = for object types?


For object types, A==b compares whether A and B are the same object!


Obviously, what we often need to do is to compare 2 objects that are not equal from the business angle, rather than want to compare whether they are the same object. So we need to override the Equals () method.


For example, a string is a requirement, so let's see how she's making a copy of Equals ():


650) this.width=650; "src=" http://s3.51cto.com/wyfs02/M00/71/1F/wKiom1XGpROR4gGHAAE-avv4FK0770.jpg "title=" Sogou _ 2015-08-09_08-55-36.png "alt=" Wkiom1xgpror4gghaae-avv4fk0770.jpg "/>


The steps for Obj1.equals (OBJ2) Implementation of string:


First, use = = See, obj1 and Obj2 is not the same object, if so then certainly equals!


Second, are they the same type? Is it the same length?


Thirdly, start by character = = comparison, if there is a difference, you can get the results, otherwise continue to compare.


Sentiment:


Later, when we go to implement the Equals method of the custom class, it is not necessary to consider the following:


Are they the same object?


Are they the same data type?


What are the key attributes of their own, and do you get a quick conclusion by comparing these key attributes?




Topic Two: Equals and hashcode


Hashcode (), like Equals (), is defined in object, let's take a look:


650) this.width=650; "src=" http://s3.51cto.com/wyfs02/M02/71/1B/wKioL1XGqsvShSNTAAAbVHQbwxw333.jpg "title=" Sogou _ 2015-08-09_09-11-31.png "alt=" Wkiol1xgqsvshsntaaabvhqbwxw333.jpg "/>


Unfortunately, in object he is a native call, and we still look at how the hashcode in string is implemented:


650) this.width=650; "src=" http://s3.51cto.com/wyfs02/M02/71/1F/wKiom1XGqXSAxWzcAACu_Bl9a64965.jpg "title=" Sogou _ 2015-08-09_09-14-19.png "alt=" Wkiom1xgqxsaxwzcaacu_bl9a64965.jpg "/>


Analysis:


First, it can be seen that once a string in the call Hashcode method, then the hash property will be assigned once, then call this hashcode method again, will directly return the hash attribute, and no longer calculated.


Second, from the Hashcode method inside the for loop can be seen, this hash value, is a composite value, is a synthesis of each character calculated.


Idea:


If 2 strings of their characters are exactly the same, then obviously their hashcode should be the same!


If 2 strings have different characters, will the hashcode be different? According to the above analysis, the hashcode is a comprehensive value, the character content is different, can be obtained exactly the same hashcode!


If Hashcode is the same, it will not come to any conclusion!


If the hashcode is different, then for string, their character content will certainly differ!



Relationship:


The comparison of the character contents of string is exactly the Equals method, so what is the relationship between equals and hashcode?


Previously, I thought that customizing a class should rewrite these 2 methods, they should be "natural pair". Not really!


The above topic, in fact, has shown that we rewrite the Equals method is to achieve 2 objects from the business perspective of the comparison, what is the hashcode do?


We know that algorithms are based on numbers, such as hash algorithms. In the map, it is clear that if key is an object, then this object should implement hash lookup and write, but he is an object ah, he should provide a number, in order to implement the hash algorithm!


In other words, hashcode is to give the object a number, this number is used in the hash of this data structure, to achieve fast positioning objects with! Hashcode to locate the linked list, we still have to use equals to compare the loop list.


That equals and hashcode actually have nothing to do with, not to be together, one is to compare the object is not business equality, one is to hash fast location and exist.



Topic Three: = = Puzzle of string


Let's take a look at the code:


650) this.width=650; "src=" http://s3.51cto.com/wyfs02/M02/71/1F/wKiom1XGtKTxITK5AACRhBmhr74708.jpg "title=" Sogou _ 2015-08-09_10-02-01.png "alt=" Wkiom1xgtktxitk5aacrhbmhr74708.jpg "/>


The result is:


True

False


For string, equals we can not make any mistake, but = = is often let us confuse the place!


First, string has optimization behavior at compile time


For example, String s = "a" + "B"; This is already the case in the generated class file:


String s = "AB";


So, in the code above, will S4 be "ABC" at compile time? No, because S2 is a variable that can only be determined during run time, and there is no mandatory constraint that he cannot change. and S5 in the compilation period has been identified as "ABC", because S3 is final, will not change!


Is that right?


Let's take a look at the disassembly Command JAVAP command:


650) this.width=650; "src=" http://s3.51cto.com/wyfs02/M02/71/1F/wKiom1XGufqQOkrsAAMBToUUQkA377.jpg "title=" Sogou _ 2015-08-09_10-24-46.png "alt=" Wkiom1xgufqqokrsaambtouuqka377.jpg "/>


Many instructions, I do not understand, we only see can understand the place, or guess a guess ~


From 0 to 8, according to the comment string ab, should be corresponding to the code


650) this.width=650; "src=" http://s3.51cto.com/wyfs02/M00/71/1B/wKioL1XGvLPif8HqAAA3xNvyUos267.jpg "title=" Sogou _ 2015-08-09_10-27-51.png "alt=" Wkiol1xgvlpif8hqaaa3xnvyuos267.jpg "/>


This also verifies that the fact that string has a compile-time merge.



From 9 to 28, a new operation has occurred, as well as append, which should correspond to:


650) this.width=650; "src=" http://s3.51cto.com/wyfs02/M01/71/1F/wKiom1XGuyeDPjpxAAAWR85yXxU835.jpg "title=" Sogou _ 2015-08-09_10-29-49.png "alt=" Wkiom1xguyedpjpxaaawr85yxxu835.jpg "/>


This shows that for string, the variable and constant of this "+" operation, actually at the bottom is made a StringBuilder to append, and finally in a ToString get!


From 30 to 32, according to the comment string abc, it should correspond to the code:


650) this.width=650; "src=" http://s3.51cto.com/wyfs02/M00/71/1C/wKioL1XGvhzwTwYqAAARxH8m2Ec650.jpg "title=" Sogou _ 2015-08-09_10-33-57.png "alt=" Wkiol1xgvhzwtwyqaaarxh8m2ec650.jpg "/>


This also shows that the final variables and constants of this "+" operation, directly compiled merge!



Second, the concept of a constant pool exists in string


String constants that are determined during compilation are present in the string pool and are guaranteed to be globally unique. That is, in the above code, S1/S2 points to the same string in the string pool.


Believe that the string after the = = will not be confused, hehe ~



Topic Four: String + VS stringbuffer.append who is faster?


We all say, stringbuffer.append good, she is faster?


According to the analysis of topic three, the "+" of string may be merged during compilation, while Stringbuffer.append is the operation that must be performed during the run, it is clear that from this point of view, the string "+" should be faster!


So, what happened before?


650) this.width=650; "src=" http://s3.51cto.com/wyfs02/M02/71/1F/wKiom1XGwMXhOFzEAACC08FRUZQ515.jpg "title=" Sogou _ 2015-08-09_10-53-47.png "alt=" Wkiom1xgwmxhofzeaacc08fruzq515.jpg "/>


For the first for loop, notice that the

s + = i;

Based on the above analysis, this is to occur with the new stringbuilder,append,tostring operation.

That is, we have a new operation in a large for loop! It's unbelievable! It's not what we expected!

We do not consider the StringBuilder expansion mechanism, to know that with the loop, the string content is getting bigger, new garbage objects are more and more large, may not have enough memory, the GC to start busy! This should be the reason for the slow performance of the program.


For a second for loop,

There is no new operation, although it involves the expansion, but not so much rubbish.



This blog is here, harvest a lot, hope to everyone also helpful ~


This article is from the "Hard Struggle" blog, please make sure to keep this source http://zhangfengzhe.blog.51cto.com/8855103/1683059

Java Foundation Series -01-starting from ==/equals/hashcode

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.