Q&A
== and equals
For basic data types, == is used to compare “values” for equality; For reference types, it is used to compare whether reference addresses are the same. = equals ();
public boolean equals(Object obj) {
return (this == obj);
}
Copy the code
In fact, the comparison is whether the reference is consistent. Overrides the equals method in String to compare the values of two strings.
Public Boolean equals(Object anObject) {return true if (this == anObject) {return true; } // Compare the contents of strings if (anObject instanceof String) {String anotherString = (String)anObject; int n = value.length; if (n == anotherString.value.length) { char v1[] = value; char v2[] = anotherString.value; int i = 0; while (n-- ! = 0) { if (v1[i] ! = v2[i]) return false; i++; } return true; } } return false; }Copy the code
The benefits of making strings final
- security
- The efficiency of
The string constant pool can be realized only when the string is immutable. The string constant pool can cache the string for us and improve the running efficiency of the program.
Char [] final indicates that the stored data cannot be modified. But: While final means immutable, just because the reference address is immutable does not mean that the array itself is immutable.
StringBuilder and StringBuffer
- The String type is immutable, and String concatenation performance is poor.
- StringBuilder is not thread-safe and can be used to concatenate strings in non-concurrent environments.
- Stringbuffers use synchronized for thread safety, so they don’t perform very well.
See the StringBuffer source code below
@Override
public synchronized StringBuffer append(Object obj) {
toStringCache = null;
super.append(String.valueOf(obj));
return this;
}
@Override
public synchronized StringBuffer append(String str) {
toStringCache = null;
super.append(str);
return this;
}
Copy the code
The String is stored
The difference between new String() and direct assignment:
-
The direct assignment method first looks for the value in the string constant pool, and if so, points the reference directly to the value. Otherwise, it creates the reference in the constant pool and then points the reference to the value.
-
The new String() method must create a String object on the heap and then check the constant pool to see if the value of the String already exists. If not, the String will be created in the constant pool and the value referenced to the String will be pointed to
String s1 = new String(“Hello World”); String s2 = s1.intern(); String s3 = “Hello World”; String s4 = “Hello ” + “World”; System.out.println(s1 == s2); //false System.out.println(s1==s3); //false System.out.println(s2==s3); //true System.out.println(s3==s4); //true System.out.println(s2==s4); //true