標籤:重載 lis contains index 情況 code 原因 本質 har
一、字串
1. += 重載符號 與 concat
str1 += str2 :底層用的 StringBuilder 效率更高,但是不夠靈活,在某些情況下效率反而較低。
str1 = new StringBuilder().append(str1).append(str2).toString();
concat:返回一個新的字串,在字串很少時,效率稍高。
StringBuilder:使用 append 拼接,在多段字串拼接時效率高。
@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));}
輸出結果
7289 | 1593 | 5
2.比較 String、HashSet、List 中的 contains 方法
其中, String、List 都使用了 indexOf 方法,本質是遍曆,時間效率為 O(n)。而 HashSet 使用了計算 hash值的方式,時間效率為 O(1) 層級。
3.String 中為什麼需要 hashCode 方法?
從String 源碼可以看到其底層實現是 char[],即本質是字元數組。包括索引及大部分功能實現都是使用數組。
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; }
為什麼還需要 hash 值呢?原因是 String 可以作為 HashSet、HashMap 容器的 key,因此需要擷取 key的哈系值。
Java 中字串與 []byte 位元組數組