JAVA中的StringBuffer與包裝類

StringBuffer(字符串緩衝區)
StringBuffer是線程安全的 可變的序列
程序會給StringBuffer一個默認的容量(理論值)—->16
但當你往StringBuffer中加入更多的東西時 程序又會自動幫StringBuffer添加容量 所以StringBuffer是一個可變的序列

如何往StringBuffer中添加字符或者字符串呢?
添加—>append(默認從最後一個字符開始添加)

StringBuffer sb = new StrigBuffer();
sb.append("helloworld");
System.out.println(sb);

輸出

helloworld

這樣我們就往一個空的StringBuffer中添加了helloworld

插入—>insert

Stringbuffer sb = new StringBuffer();
sb.append("helloworld");
sb.insert(5,"znb");
System.out.println(sb);

輸出

helloznbworld

這樣就在helloworld的第五個下標開始插入了znb

刪除—>delete/deleteCharAt

Stringbuffer sb = new StringBuffer();
sb.append("helloworld");
sb.delete(0,5);
System.out.println(sb);

輸出

world

從下標爲0到下標爲4的字符就被刪除掉了
注意: 刪除是留頭不留尾–>首下標會被刪除 但後面的下標會往前推一個刪除(至於爲什麼 你還是問高林斯吧)

單個字符刪除

Stringbuffer sb = new StringBuffer();
sb.append("helloworld");
sb.deleteCharAt(4);
System.out.println(sb);

輸出

hellworld

下標爲4的字符被刪除

替換—>replace/setCharAt

Stringbuffer sb = new StringBuffer();
sb.append("helloworld");
sb.replace(3,5,"znb");
System.out.println(sb);

輸出

helznbworld

從下標爲3到5之間的字符串被替換成znb

單個字符刪除

Stringbuffer sb = new StringBuffer();
sb.append("helloworld");
sb.setCharAt(4,z);
System.out.println(sb);

輸出

hellzworld

把下標爲4的字符替換成了z

反轉—>reverse

Stringbuffer sb = new StringBuffer();
sb.append("helloworld");
sb.reverse();
System.out.println(sb);

輸出

dlrowolleh

整個字符串反轉過來

權限修飾符
我們現在學習到的權限修飾符有4種
分別是
public —>公開的
protected—>受保護的
default—>默認的(不添加修飾符)
private—>私有的

       本類     同包類     同包子類     不同包子類     不同包類 
public  ✅        ✅        ✅           ✅           ✅

 protected ✅    ✅       ✅           ✅           ❌

 default ✅      ✅       ✅           ❌           ❌

 private  ✅     ❌       ❌           ❌           ❌

可以看到這些修飾符在不同的類的不同權限

包裝類
我們到現在已經學過不少的基本數據類型
那麼這些基本數據類型都是可以封裝成一個類的
封裝成一個類 類中就可以寫成員方法了
一起來看一下

int             Integer
short           Short
long            Long
byte            Byte
double          Double
float           Float
char            Character
boolean         Boolean

可以看到這些基本數據類型除了int與char類型的包裝類有些不同之外 其他的數據類型都只是把首字母換成了大寫而已 所以我們主要記一下int與char的包裝類就可以了

int的包裝類Integer
Integer有自動裝箱和自動拆箱功能

Integer num = 10;  //裝箱
int num2 = num + 3;//拆箱

裝箱: 用Integer直接聲明一個int類型的數 系統會自動把這個int類型的數轉換成Integer類型
拆箱: 在int類型的賦值計算時碰到Integer 系統會幫你自動把Integer類型轉換成int類型
注意: 在拆箱中 Integer類型的值不能爲null 因爲null是不能轉換成int類型的

進制轉換—>toBinaryString/toOctalString/toHexString
分別是十進制轉換成二進制/八進制/十六進制

System.out.println(Integer.toBinaryString(250));
System.out.println(Integer.toOctalString(250));
System.out.println(Integer.toHexString(250));

輸出

11111010
372
fa

分別打印出了250的二進制/八進制/十六進制

利用字符串來創建 Integer對象(只能是數字字符串)

Integer in = new Integer("250");
System.out.println(in);

輸出

250
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章