1. String A = "ABC" and string a = new string ("ABC") are different
String A = "ABC"
When the expression is executed, it will first go to the string pool in the memory to see if there is any ABC string. If there is no painting, create one in the string pool, when string B = "ABC", A and B actually point to the same memory address space,
String A = new string ("ABC") does not go to the string pool for search. Instead, a "ABC" is created directly. Therefore, when string B = new string ("ABC, it creates another one. Therefore, a and B point to different memory spaces.
The format of string in the heap follows the copy on write principle,
String A = "ABC"
String B = "ABC"
When a = "ABC" is declared, a block of memory is allocated to "ABC" in the heap. For example, the reference address is marked as 0xff09,
When declaring B = "ABC", JVM finds that "ABC" already exists in the heap, so it will directly pay the reference address 0xff09 to B, so a = B,
When new string ("") is used, the reference addresses in the memory are all new, so different
Please tell me what is the output of the following three paragraphs of code? Why? (Guan Jian: Why)
Code 1:
Hashmap map = new hashmap ();
String A = "Ade ";
String B = "Ade ";
Map. Put (A, new Boolean (true ));
Map. Put (B, new Boolean (false ));
System. Out. println (Map. Get (a). tostring ());
System. Out. println (Map. Get (B). tostring ());
The second code:
Hashmap map = new hashmap ();
String A = new string ("Ade ");
String B = new string ("Ade ");
Map. Put (A, new Boolean (true ));
Map. Put (B, new Boolean (false ));
System. Out. println (Map. Get (a). tostring ());
System. Out. println (Map. Get (B). tostring ());
Code 3:
Hashmap map = new hashmap ();
Mystring A = new mystring ("Ade ");
Mystring B = new mystring ("Ade ");
Map. Put (A, new Boolean (true ));
Map. Put (B, new Boolean (false ));
System. Out. println (Map. Get (a). tostring ());
System. Out. println (Map. Get (B). tostring ());
Mystring is defined as follows:
Public class mystring {
String STR;
Public mystring (string Str ){
This. Str = STR;
}
@ Override
Public int hashcode (){
Return Str. hashcode ();
}
}
The first code: like the 2nd Code, both outputs false.
Because a. Equals (B ).
The key of hashmap is equal to equals instead of =.
The third code, which is true false.
Similarly, here a. Equals (B) = false.
____________________________
String A = "ABC ";
String B = "ABC ";
System. Out. println (A = B );
Output: True
======================================
String A = new string ("Ade ");
String B = new string ("Ade ");
System. Out. println (A = B );
In front, a and B point to the same string
Because New is used, it is a new string with two equal values.