Java ==,equals,hashcode, parsing (for beginners to read)

Source: Internet
Author: User
Tags comparable

1. For the Equals () and Hashcade () methods they are all methods under the Java.lang.object class, and because all classes inherit from the Objct class, All classes can use both methods .

2. For the Equals () method, first know that he is used for comparison, here I do the source code ( Note: I typed the source is the object class equals () method of the source )

public boolean equals (Object obj) {

return (this==obj);

}

Appendix: This keyword I am here to make a simple explanation, for beginners on this keyword there are a lot of people are not very understanding. the This here refers to the current object itself.

I write a code: public classs chenshun{

Public String name;

public string SetName (string name) {

This. name=name;

System.out.println (this); //Here I print this

} (Note: This code is my name variable i use color to distinguish the expression, the same color indicates that they represent the same variable)

public class a{

........

Chenshun chenshun=new Chenshun ();

Chenshun.setname ("Mighty Uncle"); //Here I dropped the SetName method in the Chenshun class

System.out.println (Chenshun);//Here I print Chenshun this object

.......

}

The result is that the two printed values are the same, and from here we can draw a message here that this refers to the object of the Chenshun, OK this is the first

Let's take a look at this source code return (this==obj); I think for "= =" "This symbol is not very strange to everyone, what! You haven't seen this symbol! 0_0

Okay, I'll just say "= =" as a little bit of a sign.

Appendix: "= =" means that the comparison is 2 Address of an object I think everyone should be aware that the type of data is divided into two large classes, value types, and reference types, and if that's not clear, I think your foundation simply don't want to

But for everyone, I'm going to have to explain, look at the code.

Borrowing the classes defined above

Chenshun Chenshun =new Chenshun ();

Do not underestimate this sentence, there are a lot of interview examiners will ask you, this sentence to do what, if you do not understand, then hehe!

First I'm going to say two things, heap and Stack (stack), you can first understand that they are the two storage space respectively.

Okay, let's go back to the code.

Chenshun Chenshun; This is called a declaration, and I declare a chenshun type variable called Chenshun .

New Chenshun ();//This is called Create, I created a Chenshun object .

Chenshun=new Chenshun ();//The Object "assignment " to chenshun this variable, in fact, I personally think that said is not very accurate. The main thing is, what is this value on the value word "assignment"?

Look back at this code, Chenshun chenshun=new Chenshun ();

I'll use a few words to illustrate, create a "reference" (Chenshun Chenshun), Create an "object" (New Chenshun ();), the Java model has heaps and stacks two of memory space, Put the reference in the stack, put the object in the heap "The referenced value is the object's address in the heap", "the value of the object is the actual data", this is the reference type .

Java 8 Special types of data: byte,short,int,long,char,boolean,float,double. These types are not objects whose values are directly placed in the stack of code int i=1; I put the value in the stack is 1, and the value is not the address of the object, which is the value type.

Okay, here we go. the "= =" symbol compares the address of two objects.

So look at the code:

Chenshun chenshun=new Chenshun ();

Chenshun chenshun1=new Chenshun ();

Chenshen Chenshun2=chenshun;

System.out.println (CHENSHUN==CHENSHUN1);//false

System.out.println (Chenshun2==chenshun);//true

In this way, I think you should know what he is comparing to something!

If you look carefully at what I am writing, of course limited to beginners, and see that there are no string types in the 8 basic types, I think you should have guessed that the string is not of the underlying type , as I have said before,

Java has only two data types, namely value type, and reference type, yes string is a reference type, here is a bit far, but I think it is necessary to say the string, because

There are a lot of interviewers who like to ask this question.

String, which I think we all know, is a string, and if you write a string, you can throw it right away.

Look at the code:

String x= "ABC";

Yes, it's simple, but do you know anything about it? I think a lot of beginners don't know, but the interviewer asks, you just don't know how to answer.

Well, you can understand the string, the smell of the string, is a lot of characters connected together , you would like to think, I am what this answer, I just want to say that this is the definition of the string

Let's see, the string is a string that is concatenated with many characters, and that's the answer.

Don't look at us. Source code:

Java.lang.String

Public Final Class String implements Java.io.Serializable, Comparable<string>, charsequence{ // Note that this line of code I marked the location of red, I think you should know the purpose of this keyword.

.........

Public String () {

This.value = new Char[0]; See no, new char[0], create an empty character array, you defy me, this proves what I said above, the so-called string is a lot of strings together

}

........

}

About more string I'm not going to go into this anymore. In-depth statement, let's get back to the point, I have the time to write an article about the string of a detailed out

Some people will ask, you say the comparison of how things will pull up on the string above, I just want to answer, string is a special object of comparison, we want a special answer.

Look at the code:

String x= "ABC";

String y= "ABC";

String K=new string ("abc");

String H=new string ("abc");

String m=k;

System.out.println (x==y);//What is the result?

System.out.println (x==k);//What is the result?

System.out.println (k==h);//What is the result?

System.out.println (m==k);//What is the result?

Think carefully.

The answer is: true,false,false,,true

Some people, thinking, I'm so damn unscientific. Why is the value of x==y true, don't you say that string is a reference type? That string x= "abc"; and String y= "ABC" not created two objects?

I want to tell you this, haha you are too naïve, here is an interviewer often ask questions, string is not a variable type, a: "No!", string is an immutable type of

The nature of the string type is char[]

Do you remember what I wrote about the string source code above?

Public String () {

This. value=new char[0];

}

On the Value property here, in the string class, the Value property is defined as: Private final Char value[]; ╮(╯▽╰)╭ don't blame me for the depth of the routine, this is no way, not so pit you, you can hardly remember.

Well, the problem is, since it is immutable, we sometimes like to use the string to define a random, so that the memory will cause a lot of consumption, how to do? Sometimes the same string is defined repeatedly!

Well, Java helped us come up with a way, as long as your program is running, I'll open up a zone (Stringpool) also called a string pool.

The string pool is used to hold the various strings produced by the runtime, and the strings in the pool do not exist duplicates. Ok this is the reason, there is a duplicate string he will directly refer to the string in the pool, so

System.out.println (x==y); The result is true because when the string x= "ABC" is created, the strings are put into the string pool, and when you string y= "abc", Java Goes to

String in the pool to find if there is an "ABC", If there is "ABC" will be the memory address of the string directly to Y, OK this is why x==y.

Then some people ask again, then why is the result of X==k is false, that is because of the new keyword caused, you can remember that in Java as long as the use of the new keyword to create an object, you will be in (heap or stack) to create a new object, in other words, The object created by the New keyword is in the heap or stack, String x= "abc", so the code is generated in the String pool, the position is not the same, so the result is false.

Such a general "= =" Comparison is almost speaking, some knowledge needs to Baidu, Baidu is your best teacher!

And back to what I said before Equals (), (finally), in order to avoid you going up, then I'm playing the source of equals () in the object class

Look at the code:

public boolean equals (Object obj) {

return (this==obj);

}

You're going to be surprised. Here is the = = symbol, how and I actually use a bit different ah, since is the = = symbol, then I also use what equals (), direct = = can be.

If you think so, okay, I'm not talking.

Look at the code:

String str= new String ("abc");

String Str1=new string ("abc");

System.out.println (Str.equals (STR1));//What is the result? Think carefully.

The answer is: true

WTF, this is different from the previous analysis.

Another thing to say here is that string overrides the Equals () method.

Look at the code:

Java.lang.String public final class String  implements Java.io.Serializable, Comparable<string>    charsequence{. Public Booleam equals (Object anobject) {if (This==anobject) {return true; if (anobject instanceof String) {//The INSTANCEOF keyword here is used to determine if a reference-type variable points to an object that is an instance of a class (or interface, abstract class, parent class), String anotherstring      = (String) anobject;      int n=value.length;        if (n==anotherstring.value.length) {char v1[] = value;        Char v2[] = Anotherstring.value;        int i = 0;          while (n--! = 0) {if (V1[i]! = V2[i]) return false;        i++;      } return true;  }} return false; }  ........  }

  

It can be seen that this is a rewrite of equals (), and here is a comparison of whether two strings are the same, OK, but one thing to remember is that if you rewrite equals () it is necessary to rewrite hashcode ();

Next, let's take a look

The Hashcode () method in the object class, which I'll say later in the name Hashcode ()

Look at the code:

Java.lang.Object

Public native int hashcode ();//In the object class is such a line of code, pay attention to my red keyword here native, OK, for beginners, this keyword is really too little, basically do not use the keyword, But I'm still here to explain the use of this keyword a little bit.

To know that Java is not a perfect language, Java is not directly accessible to the bottom of the operating system, how to do, the C language can ah, then well, then I called C to help me in the bottom to do some operations, but how I let C and I Java communication, this time we use the native keyword, This is like a Java and C interface between, in fact, Java is on different platforms to use different native method to achieve access to the operating system, which actually involves the bottom of Java, beginners now do not have to go deep, Here you're like I'm calling a C-written hashcode () method here.

OK, let me get to know Hashcode ();

Let's take a look at the authoritative note (official note)

    1. hashcode method returns the hash code value of the object. This method is supported to provide some advantages to the hash table, such as the Hashtable provided by,java.util.hashtable . &NBSP;&NBSP; The general contract for
    2. hashcode  is:    
    3. during  Java  application execution, When the  hashCode  method is called multiple times on the same object, the same integer must be returned consistently, provided that the information used in the  equals  comparison on the object has not been modified. The integer does not need to be consistent from one execution of an application to another execution of the same application.    
    4. If two objects are equal according to the  equals (object)   method, then the   is called on each object in two objects. The hashcode  method must produce the same integer result. &NBSP;&NBSP;&NBSP
    5. The following conditions are not   required: If two objects are not equal according to the  equals (java.lang.Object)   method, the call on any of the two objects The  hashCode  method is bound to produce different integer results. However, programmers should know that generating different integer results for unequal objects can improve the performance of the hash table.    
    6. In fact, the  hashCode  method defined by the  Object  class does return different integers for different objects. (This is typically done by converting the object's internal address to an integer, but the  JavaTM  programming language does not require this implementation technique.) )  

It's a little too official for beginners, right, so take a look at the summary below (someone else wrote, I CTRL + C came, this is the micro Bo I read before, I think the summary is very beautiful)

1.hashCode is primarily used for quick lookups, which you can understand as an index , such as finding Hashtable,hashmap,hashcode is primarily used to determine the storage address of an object in a hash storage structure. .

2. If two objects are the same and are applicable to the Equals (Java.lang.Object) method, then the hashcode of the two objects must be the same

3. If the Equals method of the object is overridden, the object's hashcode is also rewritten as much as possible, and the object used by the hashcode must be consistent with the use of the Equals method, otherwise it will violate the 2nd mentioned above.

4. Two objects of the same hashcode, does not necessarily mean that two objects are the same, that is not necessarily applicable to the Equals (Java.lang.Object) method, only can be described in the hash storage structure, such as Hashtable, they " stored in the same basket. "

All right, this is the summary, I have a shameless smile.

Again, the hashcode is used for lookup purposes, and equals is used to compare the equality of two objects. The following is a copy of the message from someone else's post:

1.hashcode is used to find, if you have learned the data structure you should know, in the Find and sort this chapter has  such a place in memory such as  0  1  2  3  4  5  6  7    and I have a class, this class has a field called ID, I want to put this class in one of the above 8 locations, if not hashcode and arbitrary storage, then when looking for the need to go to these eight locations to find, or using a two-way algorithm.  But if you use hashcode that will improve the efficiency a lot.  we have a field called ID in this class, then we define our hashcode as id%8, and then we store our class in the place where we get the remainder. For example, our ID is 9, 9 except 8 of the remainder is 1, then we put the class exists 1 this position, if the ID is 13, the remainder is 5, then we put the class at 5 this position. In this way, the remainder can be found directly by ID in addition to 8 when the class is looked up.    2. But if the two classes have the same hashcode what to do (we assume that the ID of the class above is not unique), such as 9 divided by 8 and 17 divided by 8, the remainder is 1, then this is not legal, the answer is: can do so. So how do you judge it? At this point, you need to define equals.  in other words, we first determine whether two classes are stored in a bucket by hashcode, but there may be many classes in the bucket, then we need to find our class in this bucket by equals.  so. overriding Equals (), why rewrite Hashcode ()? If you want to find  something in a bucket, you have to find the bucket first, you don't have to rewrite hashcode () to find the bucket, the Light rewrite equals () What's the use?  

Here I put out Java.lang.String class of Hashcode source

  public int hashcode () {        int h = hash;        if (h = = 0 && value.length > 0) {            char val[] = value;            for (int i = 0; i < value.length; i++) {                h = + * H + val[i];            }            hash = h;        }        return h;    }

  

Finally, let me summarize.

1. For = =, if the variable that is acting on the base data type, directly compares the value of its stored values for equality;

If you are acting on a variable of a reference type, the address of the object to which you are pointing is compared

2. For the Equals method, note that the Equals method cannot act on a variable of the base data type

If the Equals method is not overridden, the address of the object to which the variable of the reference type is to be compared;

Classes such as String, date, and so on have overridden the Equals method to compare the contents of the object being pointed to.

3.hashCode is used to find, if you rewrite the equals, then please rewrite the hashcode, or put into the hashset will appear problems, specific what problems you want to try yourself.

 

Well, the blog is written here, Ma Ah, exhausted me, if I have nothing to write right please be sure to point out, thank you ~~~~~~? (^?^*)

Java ==,equals,hashcode, parsing (for beginners to read)

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.