== vs equals()== 比較引用地址;equals() 比較內容。除非檢查是否為同一對象,否則永遠用 equals()。了解字符串駐留機制(intern())有助於理解 == 有時會返回 true 的情況。
char[] 而非 StringString 不可變,創建後常駐內存直到 GC,風險大。char[] 可顯式清零(Arrays.fill(chars, '\0')),使用後立即銷毀,減少內存洩露風險。
switch 中能否用 StringJDK 7+ 支持。switch (str.toLowerCase()) { case "a": ... }
JDK 6 及之前不支持,需用 if-else 或枚舉。
int n = Integer.parseInt("10"); 簡單高頻,易被忽略。
String[] arr = str.split("\\s+"); \\s 匹配空格、制表符、換行等所有空白字符,+ 合併連續空白。
substring() 內部機制JDK 6:返回共享底層 char[] 的新 String(偏移+計數),未創建新數組。大字符串取小子串會阻礙大字符串 GC。
解決:str.substring(m,n) + "" 強制複製。
JDK 7+:substring 直接複製新 char[],無共享問題。
String vs StringBuilder vs StringBufferString 不可變。StringBuilder 可變、非線程安全、性能最佳。StringBuffer 可變、線程安全 (synchronized)、性能稍差。Python 風格 "ab" * 3 Java 無內置。用 Apache Commons Lang:String repeated = StringUtils.repeat("abcd", 3); // abcdabcdabcd
String str = "Sep 17, 2013";
Date date = new SimpleDateFormat("MMMM d, yy", Locale.ENGLISH).parse(str);
// Tue Sep 17 00:00:00 EDT 2013
注意 SimpleDateFormat 非線程安全,多線程用 ThreadLocal 或 JDK 8 DateTimeFormatter。
Apache Commons Lang:int n = StringUtils.countMatches("11112222", "1"); // 4
boolean allUpper = str.matches("[A-Z]+");
// 或
boolean allUpper = str.chars().allMatch(Character::isUpperCase); // JDK 8+
| 題號 | 核心知識點 | 關鍵 API / 庫 |
|---|---|---|
| 1 | 引用 vs 內容比較 | equals() |
| 2 | 敏感數據內存安全 | char[], Arrays.fill |
| 3 | Switch 支持版本 | JDK 7+ |
| 4 | 字符串轉基本類型 | Integer.parseInt |
| 5 | 正則分割空白 | split("\\s+") |
| 6 | substring 實現差異 | JDK 6 共享 / JDK 7+ 複製 |
| 7 | 三大構建器選擇 | 單線程 StringBuilder |
| 8 | 重複字符串 | StringUtils.repeat |
| 9 | 日期解析 | SimpleDateFormat / DateTimeFormatter |
| 10 | 字符計數 | StringUtils.countMatches |