Understanding of "Java Fundamentals" "equals" and "= ="

Source: Internet
Author: User

Briefly:
= =: used for basic types and reference types: When used for basic types, is the comparison value the same; When used for reference types, the comparison object (memory address) is the same;
The object class in the Equals:java.lang package has the public boolean equals (Object obj) {return (this = = obj)} method, which compares two objects for equality;

Therefore, for the reference type to a certain extent, "= =" and "equals" function is consistent, are compared to the object (memory address) is the same;

1, the JDK common class "= =" and "Equals ()" The difference:

The common class string in the JDK, the wrapper type of the underlying type, all override the Equals () method, so the result in the following example is:

 string overrides the object's Equals () method to compare characters of the same index (the comparison of the underlying type char "= =")  //  also found that the underlying type of encapsulation type, also overrides the Equals () method, so the usual use of equals () gives us the impression that the value of the comparison itself is the same;  // char[character], Byte[byte], Short[short], Int[integer], Long[long], float[float], Double[double], Boolean[boolean]   string a = new  String ("s" ); String b  = new  String ("s"  // print true  System.out.println (A = = B); // print false  

Therefore, in the comparison of reference types, the personal feeling equals () method is the "= =" Supplement, complete "= =" do not do the function (compare the contents of the object is the same)!

2. The details of "= =" in the String class:

For reference types, the "= =" Comparison object (memory address) is the same, but the result in the following example does not exactly follow the above description:

New String ("s"= "s"= "s"//print True//print False

The reason: Within the JVM, there is a string pool, which holds many string objects and can be used for sharing.

Its procedure: If you want to create the next string object, the JVM will first look in the string pool, whether there is a corresponding string object, and if so, returns a reference to the object to be created for the object that already exists.

If it does not exist, a new object is created and a new object reference is returned to the object reference to be created. So the c = = d return value is true in the example.

For string a = new string ("s"), there are "s", a two string objects, and a is not stored in the string shared pool, so the example c = = A return value is False

The above description also applies to the encapsulation class of the basic type such as Integer;

3, the ordinary Class of "Equals ()" Rewrite:

Inspired by the string class, we can also override the Equals () method of a custom class, as in the following example:

 Public classEquals {PrivateString name = ""; Private intAge = 0;  PublicEquals (String name,intAge ) {         This. Name =name;  This. Age =Age ; } @Override Public Booleanequals (Object obj) {if( This==obj) {            return true; }        if(objinstanceofEquals) {Equals equ=(Equals) obj; return  This. Name.equals (Equ.name) && This. Age = =Equ.age; }        return false; } @Override Public inthashcode () {return31 * This. Name.hashcode () + ((Integer) This. Age). Hashcode (); }     Public Static voidMain (string[] args) {Equals eq1=NewEquals ("s", 3); Equals EQ2=NewEquals ("s", 3);        System.out.println (Eq1.equals (EQ2)); System.out.println (eq1==EQ2); }}

Overriding equals must be noted:
1. Reflexivity: For any reference value x,x.equals (x) must be True
2. Symmetry: for arbitrary reference values x and Y, when X.equals (y) returns True,y.equals (x) also must return True
3. transitivity: For any reference value x, Y, and Z, if X.equals (y) returns True, and Y.equals (Z) also returns True, then X.equals (z) must also return true
4. Consistency: For arbitrary reference values x and Y, if the object information used for the equals comparison has not been modified, multiple calls to X.equals (Y) either consistently return TRUE or return false uniformly
5. Non-nullability: for any non-null reference value x,x.equals (NULL) must return FALSE
6. Rewrite hashcode: It is best to rewrite the Hashcode () method at the same time, otherwise two equivalent objects may get different hashcode values, resulting in problems using the collection framework;

Hashcode Description: JDK based on the address of the object or a string or a numeric value of the int type, this method is mainly to improve the performance of the hash table (such as the java.util.Hashtable provided by the hash table);

By analyzing the Get () method of Hashtable, we can see that the key key must satisfy the Hashcode value and key value to obtain the corresponding value key.

 Public object get (Object key) {    hashtableentry e;     = table;     int hash = Key.hashcode ();     int index = (hash & 0x7FFFFFFF)% tab.length;      for null; E = e.next)        if ((E.hash = = hash) && e.key.equals (key)            )return  e.value;         return NULL ;}        

Java Fundamentals "equals" and "= =" Understanding

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.