We all know that the final modifier variable becomes constant, but when a variable is decorated with the final keyword, is the reference immutable or does the referenced object not change?
Let's look at the code below:
/** * verifies that a final modified variable is a reference cannot be changed, or that the referenced object cannot be changed * StringBuilder thread is unsafe but fast * reference initialization cannot be changed--- Does not mean that the value of the variable is immutable, but instead points to the variable address immutable * @author Tomato * */public class Testfinal {public static void main (string[] args) {final STRINGB Uilder sb = new StringBuilder ("haha");//The hashcode value of the same object is the same System.out.println ("SB's content is:" +SB); The hash code for SYSTEM.OUT.PRINTLN (sb+ ") is:" +sb.hashcode ()); Sb.append ("I have Changed"); System.out.println ("SB's content is:" +SB); The hash code for SYSTEM.OUT.PRINTLN (sb+ ") is:" +sb.hashcode ()); System.out.println ("-----------------hash Value-------------------"); Testfinal test = new testfinal (); System.out.println (Test.hashcode ()); System.out.println (Integer.tohexstring (Test.hashcode ())); System.out.println (Test.getclass () + "@" +integer.tohexstring (Test.hashcode ())); System.out.println (Test.getclass (). GetName () + "@" +integer.tohexstring (Test.hashcode ()));//define ToString in the API () Equivalent to GetClass (). GetName () + ' @ ' + integer.tohexstring (hashcode ())//The return value is a string representation of the object. System.out.println (Test.tostring ());}}
The code results are:
The content of SB is: haha
The hash code for the haha is: 1928052572
The content of SB is: haha i have changed.
haha I've changed. The hash code is: 1928052572
-----------------Hash Value-------------------
1398828021
53606bf5
class [email protected]
[Email protected]
[Email protected]
It can be seen that the content in StringBuilder has changed and the hash encoding pointed to has not changed, in Java each object has its own unique hash code, according to this code can find the relevant object, that is, according to this code you can uniquely determine the object.
Thus, when a variable is decorated with the final keyword, the reference variable cannot be changed, and the contents of the object to which the reference variable refers can be changed.
Reprint must indicate the source.
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
A final modified variable is a reference to an object that cannot be changed or referenced.