包裝類、字符串

1. 裝箱: 把基本數據類型轉換成包裝類

int t1 = 1;
// 自動裝箱
Integer t2 = t1;
// 手動裝箱
Integer t3 = new Integer(t1);

2. 拆箱:把包裝類轉換成基本數據類型

int t1 = 1;
// 自動裝箱
Integer t2 = t1;
// 自動拆箱
int t3 = t2;
// 手動拆箱
int t4 = t2.intValue();

3. 基本數據類型和字符串之間轉換

// 基本數據類型轉換爲字符串
int t1 = 1;
String t2 = Integer.toString(t1);
// 字符串轉換爲基本數據類型
// 包裝類的parse
int t3 = Integer.parseInt(t2);
// 包裝類的valueOf,先將字符串轉換爲包裝類,再通過自動拆箱完成基本類型轉換
int t4 = Integer.valueOf(t2);

4. 自動裝箱需要注意的點

  • 緩衝區對象池 -128 < 參數 < 127
    • Integer具備對象池,如果在對象池中有這個參數,則直接產生;如果沒有,則實例化Integer
    • Double和Float不具備對象池

5. String常用方法

  • int length() 返回當前字符串的長度
  • int indexOf(int ch) 查找ch字符在該字符串中第一次出現的位置
  • int indexOf(String str) 查找str子字符串在該字符串中第一次出現的位置
  • int lastIndexOf(int ch) 查找ch字符在該字符串中最後一次出現的位置
  • int lastIndexOf(String str) 查找str子字符串在該字符串中最後一次出現的位置
  • String substring(int beginIndex) 獲取從beginIndex位置開始到結束的子字符串
  • String substring(int beginIndex, int endIndex) 獲取從beginIndex位置開始到endIndex位置的子字符串
  • String trim() 返回去除了前後空格的字符串
  • boolean equals(Object obj) 將字符串與指定對象比較,返回true或false
  • String toLowerCase() 將字符串轉換爲小寫
  • String toUpperCase() 將字符串轉換爲大寫
  • char charAt(int index) 獲取字符串中指定位置的字符
  • String[] split(String regex, int limit) 將字符串分割爲子字符串,返回字符串數組
  • byte[] getBytes() 將該字符串轉換爲byte數組

6. 等於運算符與equals區別

  • 內存模型
    • 棧 - String str1
    • 常量池 - "hello world"
    • 堆 - new String("hello world")

7. 字符串的不可變性

  • String對象一旦被創建,則不能修改,是不可變的
  • 所謂的修改其實是創建了新的對象,所指向的內存空間不變

8. 字符串StringBuilder

  • String和StringBuilder的區別
    • String具有不可變性,而StringBuilder不具備
    • 當頻繁操作字符串時,使用StringBuilder
    • StringBuffer是線程安全的,StringBuilder不是,所以性能略高

9. StringBuilder常用方法

  • StringBuilder append(String str)
  • StringBuilder delete(int start, int end)
  • StringBuilder insert(int offset, String str)
  • StringBuilder replace(int start, int end, String str)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章