一、字符串
1.比較 String、HashSet、List 中的 contains 方法
其中, String、List 都使用了 indexOf 方法,本質是遍歷,時間效率為 O(n)。而 HashSet 使用了計算 hash值的方式,時間效率為 O(1) 級別。
2.String 中為什么需要 hashCode 方法?
從String 源碼可以看到其底層實現是 char[],即本質是字符數組。包括索引(indexOf)及大部分功能(比如 equals 方法)實現都是使用數組。
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的哈系值,貌似 switch case 方法也是根據 hash 來判別,而不是用 equals。
3.compareTo
實現了 Comparable 接口,此接口強行對實現它的每個類的對象進行整體排序。這種排序被稱為類的自然排序,類的 compareTo 方法被稱為它的自然比較方法。String 里是通過數組索引實現的字典序。
實現此接口的對象列表(和數組)可以通過 Collections.sort(和 Arrays.sort)進行自動排序。實現此接口的對象可以用作有序映射中的鍵或有序集合中的元素,無需指定比較器。
4. []char 數組的打印語句與普通數組的打印語句
public void test() {
String str = "Good Java";
char[] chars = str.toCharArray();
System.out.println(chars);
System.out.println(Arrays.toString(chars));
byte[] bytes = str.getBytes();
System.out.println(bytes);
System.out.println(Arrays.toString(bytes));
int[] intArr = new int[]{3, 4, 2, 5};
System.out.println(intArr);
System.out.println(Arrays.toString(intArr));
}
輸出結果
Good Java [G, o, o, d, , J, a, v, a] [B@47089e5f [71, 111, 111, 100, 32, 74, 97, 118, 97] [I@4141d797 [3, 4, 2, 5]
說明:字符數組 print 是字符串,而非字符數組 print 一般是數組地址。
5.獲取字節數組與獲取字符數組
//使用指定的字符集將此 String 編碼為 byte 序列,並將結果存儲到一個新的 byte 數組中。 byte[] getBytes(String charsetName) //將字符從此字符串復制到目標字符數組。 void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin) //將此字符串轉換為一個新的字符數組。 public char[] toCharArray()
6. 其它方法
boolean endsWith(String suffix) boolean startsWith(String prefix, int toffset) boolean matches(String regex) String trim() // 返回字符串的副本,忽略前導空白和尾部空白。 String replaceAll(String regex, String replacement) String[] split(String regex, int limit) static String format(String format, Object... args) byte[] getBytes(String charsetName) char[] toCharArray() /* StringBuilder 的相關方法 */ StringBuilder(int capacity)//默認容量為 16 StringBuilder append(double d) int length() int capacity() StringBuilder reverse()
7 “重載符號”+、+= 與 concat
str1 += str2 :底層用的 StringBuilder 效率更高,但是不夠靈活,在某些情況下效率反而較低。
str1 = new StringBuilder().append(str1).append(str2).toString();
concat:返回一個新的字符串,在字符串很少時,效率稍高。
StringBuilder:使用 append 拼接,在多段字符串拼接時效率高。
@org.junit.Test
public 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
8. 字面量與 intern 方法
待更新...
