Java Object 類和 String 類常用 API
一、Object 類核心方法
Object 類是 Java 中所有類的超類,提供了以下重要方法:
1. 基本方法
方法 描述 重寫建議 public boolean equals(Object obj)
對象相等性比較 必須重寫(同時重寫hashCode) public int hashCode()
返回對象哈希碼 必須與equals()保持一致 public String toString()
返回對象字符串表示 推薦重寫為友好格式 protected Object clone()
創建并返回對象副本 需實現Cloneable接口
2. 線程相關方法
方法 描述 public final void wait()
使當前線程等待 public final void notify()
喚醒在此對象監視器上等待的單個線程 public final void notifyAll()
喚醒在此對象監視器上等待的所有線程
3. 示例代碼
@Override
public boolean equals ( Object o) { if ( this == o) return true ; if ( o == null || getClass ( ) != o. getClass ( ) ) return false ; Person person = ( Person ) o; return age == person. age && Objects . equals ( name, person. name) ;
} @Override
public int hashCode ( ) { return Objects . hash ( name, age) ;
}
@Override
public String toString ( ) { return "Person{" + "name='" + name + '\'' + ", age=" + age + '}' ;
}
二、String 類常用 API
String 是 Java 中最常用的不可變字符序列類,提供豐富的操作方法。
1. 字符串創建與基本信息
方法 描述 示例 String()
創建空字符串 new String()
String(String original)
創建字符串副本 new String("hello")
int length()
返回字符串長度 "hello".length()
→ 5boolean isEmpty()
判斷是否空字符串 "".isEmpty()
→ true
2. 字符串比較
方法 描述 示例 boolean equals(Object anObject)
內容相等比較 "a".equals("A")
→ falseboolean equalsIgnoreCase(String anotherString)
忽略大小寫比較 "a".equalsIgnoreCase("A")
→ trueint compareTo(String anotherString)
字典序比較 "a".compareTo("b")
→ -1int compareToIgnoreCase(String str)
忽略大小寫字典序比較 "A".compareToIgnoreCase("a")
→ 0
3. 字符串查找
方法 描述 示例 char charAt(int index)
返回指定索引字符 "hello".charAt(1)
→ ‘e’int indexOf(int ch)
返回字符首次出現位置 "hello".indexOf('l')
→ 2int lastIndexOf(int ch)
返回字符最后出現位置 "hello".lastIndexOf('l')
→ 3boolean contains(CharSequence s)
判斷是否包含子串 "hello".contains("ell")
→ trueboolean startsWith(String prefix)
判斷是否以指定前綴開頭 "hello".startsWith("he")
→ trueboolean endsWith(String suffix)
判斷是否以指定后綴結尾 "hello".endsWith("lo")
→ true
4. 字符串操作
方法 描述 示例 String substring(int beginIndex)
截取子串 "hello".substring(2)
→ “llo”String substring(int beginIndex, int endIndex)
截取子串(含頭不含尾) "hello".substring(1,4)
→ “ell”String concat(String str)
字符串連接 "hello".concat(" world")
→ “hello world”String replace(char oldChar, char newChar)
字符替換 "hello".replace('l','L')
→ “heLLo”String replaceAll(String regex, String replacement)
正則替換 "a1b2".replaceAll("\\d","")
→ “ab”String[] split(String regex)
按正則分割字符串 "a,b,c".split(",")
→ [“a”,“b”,“c”]String toLowerCase()
轉為小寫 "HELLO".toLowerCase()
→ “hello”String toUpperCase()
轉為大寫 "hello".toUpperCase()
→ “HELLO”String trim()
去除首尾空白符 " hello ".trim()
→ “hello”String strip()
去除首尾空白符(支持Unicode) " hello ".strip()
→ “hello”
5. 類型轉換
方法 描述 示例 static String valueOf(基本類型/對象)
將其他類型轉為字符串 String.valueOf(123)
→ “123”byte[] getBytes()
轉為字節數組(默認編碼) "hello".getBytes()
byte[] getBytes(String charsetName)
按指定編碼轉為字節數組 "你好".getBytes("UTF-8")
char[] toCharArray()
轉為字符數組 "hello".toCharArray()
→ [‘h’,‘e’,‘l’,‘l’,‘o’]
6. JDK 8+ 新增方法
方法 描述 示例 String join(CharSequence delimiter, CharSequence... elements)
靜態方法,用分隔符連接字符串 String.join("-","a","b","c")
→ “a-b-c”boolean isBlank()
判斷是否空白字符串(JDK11) " ".isBlank()
→ trueString stripLeading()
去除開頭空白(JDK11) " hello ".stripLeading()
→ "hello "String stripTrailing()
去除末尾空白(JDK11) " hello ".stripTrailing()
→ " hello"String repeat(int count)
重復字符串(JDK11) "a".repeat(3)
→ “aaa”String formatted(Object... args)
格式化字符串(JDK15) "Hi %s".formatted("Tom")
→ “Hi Tom”
三、最佳實踐
字符串比較 :總是使用 equals()
而不是 ==
比較內容字符串拼接 : 少量拼接用 +
循環內拼接用 StringBuilder
多元素拼接用 String.join()
不可變性 :記住String是不可變的,所有修改操作都返回新對象編碼注意 :處理非ASCII字符時明確指定字符編碼
四、性能考慮
字符串常量池 :字面量字符串會被放入常量池復用String s1 = "hello" ;
String s2 = new String ( "hello" ) ;
大字符串處理 :考慮使用 StringBuilder
或 StringBuffer
(線程安全)正則表達式 :復雜正則預編譯 Pattern
對象提高性能
五、常見面試問題
String、StringBuilder、StringBuffer區別?
String:不可變,線程安全 StringBuilder:可變,非線程安全,性能高 StringBuffer:可變,線程安全(synchronized方法) 為什么String設計為不可變?
安全性:作為參數傳遞時不會被修改 線程安全:天然線程安全 緩存哈希碼:只需計算一次 字符串常量池:可以安全地復用字符串 如何高效拼接字符串?
String result = "" ;
for ( int i = 0 ; i < 100 ; i++ ) { result += i;
}
StringBuilder sb = new StringBuilder ( ) ;
for ( int i = 0 ; i < 100 ; i++ ) { sb. append ( i) ;
}
String result = sb. toString ( ) ;