One, the string
1. + = overloaded Symbols and concat
STR1 + = str2: Lower- level StringBuilder are more efficient, but less flexible, and in some cases less efficient .
str1 = new StringBuilder (). Append (str1). Append (str2). toString ();
Concat: Returns a new string that is slightly more efficient when the string is small .
StringBuilder: Use append stitching, high efficiency in multi-segment string stitching .
@org. junit.testpublic void Test () { int times = 100000; String S1 = ""; String s2 = ""; StringBuilder s3 = new StringBuilder (""); Long a = System.currenttimemillis (); for (int i = 0; I < times; i + +) { S1 + = "a"; } Long B = System.currenttimemillis (); for (int i = 0; I < times; i + +) { s2 = s2.concat ("a"); } Long C = System.currenttimemillis (); for (int i = 0; I < times; i + +) { s3.append ("a"); } Long d = System.currenttimemillis (); System.out.print ((b-a) + "|" + (C-B) + "|" + (D-C));}
Output results
7289 | 1593 | 5
2. Compare contains methods in String, HashSet, List
The IndexOf method is used by String and List, which is essentially traversal, and the time efficiency is O (n). The HashSet uses the method of calculating the hash value, the time efficiency is O (1) level.
Why do I need hashcode method in 3.String?
From the string source can see its underlying implementation is char[], that is, the essence is a character array. Both the index and most of the feature implementations use arrays.
Public final class String implements XXX { private final char value[]; /** Cache The hash code for the string */ private int hash;//Default to 0 public string () { this.value = "". value; } public string (string original) { this.value = Original.value; This.hash = Original.hash; }
Why do we need hash values? The reason is that String acts as a key to the HashSet, HashMap container, so you need to get the value of the key's system.
string in Java with []byte byte array