The reason why the hash code after i ++ will change

The reason why the hash code after i ++ will change

Synchronized synchronization lock is the same object, if the object changes, it will lose its effect

First code:

public  class IntegerHashCode {
     public  static  void main (String [] args) { 
        Integer integer = 1 ;
         // System.identityHashCode: returns the original hashCode value, regardless of whether the Object object is rewritten; the hash code of the null reference is zero 
        System. out.println ("hashCode value before" ++ --- "+ System.identityHashCode (integer)); 
        integer ++ ; 
        System.out.println ( " hashCode value after ++ --- "+ System.identityHashCode ( integer)); 

    } 
}

operation result:

 It turns out that the hashCode values ​​before ++ and after ++ are not the same, why?

Let's find the reason step by step:

1. Decompile this java file

it can be discovered:

integer ++ is like this Integer integer1 = this.num, integer2 = this.num = Integer.valueOf (this.num.intValue () + 1);

2. View the source code of Integer.valueOf ()

 At this time, it was found that it was a new Integer. In this case, every ++ once, then a new object will be generated, and the hashCode value of the new object is different.

Guess you like

Origin www.cnblogs.com/mjtabu/p/12702732.html