The difference between equals,hashcode and = = in Java

Source: Internet
Author: User

1, = =

The data types in Java can be divided into two categories:

1. Basic data type, also known as raw data type

Byte,short,char,int,long,float,double,boolean the comparison between them, apply the double equals sign (= =), compare their values.

2. Reference type (class, interface, array)

When they compare with (= =), they compare the storage address in memory, so unless it is the same new object, their comparison result is true, otherwise the result is false.

The object is placed in the heap, where the object's reference (address) is stored. Thus, ' = = ' is a comparison of the values in the stack. If you want to compare the contents of objects in the heap with the same content, you should override the Equals method.

Cases:


  1. Public static void Main (string[] args) {
  2. int int1 = 12;
  3. int int2 = 12;
  4. Integer Integer1 = new Integer (12);
  5. Integer Integer2 = new Integer (12);
  6. Integer Integer3 = new Integer (127);
  7. Integer A1 = 127;
  8. Integer B1 = 127;
  9. Integer a = 128;
  10. Integer B = 128;
  11. String S1 = "str";
  12. String s2 = "str";
  13. String str1 = new String ("str");
  14. String str2 = new String ("str");
  15. System.out.println ("Int1==int2:" + (int1 = = Int2));
  16. System.out.println ("Int1==integer1:" + (int1 = = Integer1));
  17. System.out.println ("Integer1==integer2:" + (Integer1 = = Integer2));
  18. System.out.println ("INTEGER3==B1:" + (Integer3 = = B1));
  19. System.out.println ("A1==B1:" + (a1 = = B1));
  20. System.out.println ("a==b:" + (A = = b));
  21. System.out.println ("S1==S2:" + (S1 = = s2));
  22. System.out.println ("S1==STR1:" + (S1 = = str1));
  23. System.out.println ("STR1==STR2:" + (str1 = = str2));
  24. }

Output Result:

Int1==int2:true
Int1==integer1:true//integer automatically unboxing to int, so true
integer1==integer2:false//different objects, in memory storage address is different, so false
Integer3==b1:false//integer3 points to the object address of new, B1 points to the 127 address in the cache, the address is different, so false

A1==b1:true
A==b:false

S1==s2:true
S1==str1:false
Str1==str2:false

Integer B1 = 127;java at compile time, translated into integer B1 = integer.valueof (127);


  1. Public static Integer valueOf (int i) {
  2. assert Integercache.high >= 127;
  3. if (i >= integercache.low && i <= integercache.high)
  4. return integercache.cache[i + (-integercache.low)];
  5. return new Integer (i);
  6. }


Look at the source code everyone will understand that for the number between 128 to 127 will be cached, Integer B1 = 127, 127 will be cached, the next time you write an Integer I6 = 127, will be directly from the cache, will not be new. So A1==b1:true A==b:false

2. Equals

1. The default (without overriding the Equals method) Equals method calls the Equals method of the object class, whereas the Equals method of object is primarily used to determine if the object's memory address reference is the same address (not the same object). The following is the Equals method in the object class:


    1. Public Boolean equals (Object obj) {
    2. return (This= = obj);
    3. }

the definition equals = = is equivalent

2. If the Equals method is overridden in the class, then it is necessary to determine the function of the Equals method according to the specific code, and the object is generally judged by whether the object is equal by its content equality. The following is a string class that overrides equals:


  1. Public Boolean equals (Object anobject) {
  2. if (this= = anobject) {
  3. return true;
  4. }
  5. if (anobject instanceof String) {
  6. String anotherstring = (string) anobject;
  7. int n = count;
  8. if (n = = anotherstring.count) {
  9. char v1[] = value;
  10. char v2[] = Anotherstring.value;
  11. int i = offset;
  12. int j = Anotherstring.offset;
  13. While (n--! = 0) {
  14. if (v1[i++]! = v2[j++])
  15. return false;
  16. }
  17. return true;
  18. }
  19. }
  20. return false;
  21. }


The step in which the Equals method in string determines equality is:

1. Returns true if A==b is the same string object

2. If the comparison object is a string type, continue, otherwise return false

3. Determine if A and B are the same length, return false

4. Compares characters by character, and returns false if there are unequal characters

There are five points that you need to pay attention to equals again:
1 reflexivity: The return value of X,x.equals (x) for any reference value must be true.
2 symmetry: For any reference value x, Y, the return value of X.equals (Y) must be true if and only if Y.equals (x) returns a value of true;
3 transitivity: If X.equals (y) =true, y.equals (z) =true, then X.equals (z) =true
4 Consistency: If the object participating in the comparison does not change, then the result of the object comparison should not have any change
5 non-nullability: any non-null reference value x,x.equals (NULL) The return value must be false

Tips for implementing the high-quality equals method:
1. Use the = = symbol to check if the parameter is a reference to this object. If yes, returns TRUE. This is nothing more than a performance optimization, which is worth doing if the comparison operation is likely to be expensive.
2. Use the instanceof operator to check if the parameter is the correct type. If it is not, it returns false. In general, the so-called "right type" refers to the same class as the Equals method.
3. Convert the parameters to the correct type. Because the instanceof test was done before the conversion, make sure it succeeds.
4. For each "critical" field in the class, check that the field in the parameter matches the corresponding field in the object. Returns true if all of these tests are successful, otherwise false.
5. After writing completes the Equals method, check for symmetry, transitivity, and consistency.

3, Hashcode

The Hashcode () method returns a numeric value, as can be seen from the name of the method, and its purpose is to generate a hash code. The main purpose of hash code is to hash the object as a key input, it is easy to infer that we need each object hash code as much as possible, in order to ensure the hash of the access performance. In fact, the default implementation provided by the object class does guarantee that each object's hash code is different (a hash code is returned by a particular algorithm based on the object's memory address). Java uses the principle of a hash table. The hash (hash) is actually a personal name, and because he proposes a hash algorithm, it is named after his name. A hashing algorithm, also known as a hashing algorithm, is a direct assignment of data to an address based on a particular algorithm. Beginners can understand that the Hashcode method actually returns the physical address of the object store (which may not actually be the case).

Hashing functions, hashing algorithms, hash functions.
is a way to create small digital "fingerprints" from any kind of data.
The hash function maps a binary value of any length to a shorter fixed-length binary value, a small binary value called a hash value.
A good hash function rarely has a hash conflict in the input field.
=================================================================================
All hash functions have the following basic characteristics:
1: If a=b, then H (a) = h (b).
2: If a!=b, then H (a) and H (b) may get the same hash value.

Hashcode method for Object: Returns an int type


    1. Public native int hashcode ();


The role of 3.1 hashcode

To understand, you must first know the collection in Java.
In general, there are two types of collections (Collection) in Java, one is list, and the other is set. The elements within the set are ordered, the elements can be repeated, the latter elements are unordered, but the elements are not repeatable.

So here is a more serious problem: to ensure that the elements do not repeat, can two elements should be repeated based on what to judge?

This is the Object.Equals method. However, if each additional element is checked once, the number of elements that are added to the collection is much more numerous when the element is many. That is, if there are now 1000 elements in the collection, then the 1001th element joins the collection, it calls the Equals method 1000 times. This obviously will significantly reduce efficiency.
Thus, Java uses the principle of a hash table.

This way, when the collection is adding a new element,

By calling the Hashcode method of this element, you can immediately locate the physical location where it should be placed.

If there is no element in this position, it can be stored directly in this position without any further comparison;

If there is already an element in this position, the Equals method that calls it is compared with the new element, and the same is not saved, and the other addresses are hashed. So there is a conflict resolution problem here. In this way, the number of actual calls to the Equals method is greatly reduced, almost only one or two times.

4. Relationship between Eqauls method and Hashcode method

Java for the Eqauls method and the Hashcode method are defined as:

(1) The Hashcode () method is called multiple times on the same object, always returning the same integer value.

(2) if A.equals (b), then there must be A.hashcode () must be equal to B.hashcode ().

(3) if!a.equals (b), then A.hashcode () is not necessarily equal to B.hashcode (). If A.hashcode () is not always equal to B.hashcode (), the performance of hashtables is increased.

(4) A.hashcode () ==b.hashcode () a.equals (b) can be really false

(5) A.hashcode ()! = B.hashcode () a.equals (b) is false.

Above conclusion précis-writers:

1. If two objects Equals,java run-time environment will think their hashcode must be equal.
2. If two objects are not equals, their hashcode may be equal.
3, if two objects hashcode equal, they do not necessarily equals.
4, if two objects hashcode unequal, they must not equals.

Important specifications for these two methods:

Spec 1: If you override the Equals (object obj) method, it is necessary to override the Hashcode () method to ensure that two objects with the Equals (object obj) method have an equal hashcode () return value. The simple point is: "If two objects are the same, then their hashcode should be equal". Note, however, that this is only a specification, if you have to write a class to let equals (Object obj) return True and Hashcode () returns two unequal values, compile and run without error. However, this violates the Java specification, the program also buried the bug.

Spec 2: If Equals (Object obj) returns False, that is, two objects are "not the same", it is not required to call the Hashcode () method on both objects to get two different numbers. The simple point is: "If two objects are not the same, their hashcode may be the same".

5. Why overwrite equals when always overwrite Hashcode
A common source of error is the failure to overwrite the Hashcode method. In each class that overrides the Equals method, you must also overwrite the Hashcode method. If you do not do this, you will violate the general conventions of Object.hashcode, resulting in the class not working properly with all hash-based collections, such as HashMap, HashSet, and Hashtable.

1. During the execution of an application, the Hashcode method must consistently return the same integer if the information used for the comparison operation of the object's Equals method has not been modified, and the same object is called multiple times. During multiple executions of the same application, the integer returned by each execution can be inconsistent.

2. If two objects are equal according to the Equals () method, the Hashcode method that calls either object in both objects must produce the same integer result.

3. If two objects are not equal according to the Equals () method, then calling the Hashcode method of either object in both objects does not necessarily produce the same integer result. However, programmers should know that it is possible to improve the performance of a hash table by producing distinct integer results for unequal objects.

6. Summary:
1. The Equals method is used to compare the contents of an object for equality (overwrite later)

2. The Hashcode method is used only in the collection

3. When the Equals method is overridden, the comparison objects are compared by the overridden Equals method (judging whether the object's contents are equal).

4. When putting an object into a collection, first determine whether the Hashcode value to be placed on the object is equal to the hashcode value of any of the elements in the collection, and if not equal, put the object directly into the collection. If the hashcode value is equal, then the Equals method is used to determine if any of the objects in the collection are equal, and if equals does not determine equality, the element is placed directly into the collection, otherwise it is not put.

Reprint: http://blog.csdn.net/hla199106/article/details/46907725

The difference between equals,hashcode and = = in Java

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.