一、圖解Java中String不可變性,javastring

來源:互聯網
上載者:User

一、圖解Java中String不可變性,javastring

這裡有一堆例子來說明Java的String的不可變性。

1、聲明一個String

String s = "abcd";



s 變數儲存string對象的引用,下面的箭頭解釋成儲存了哪個對象的引用。

 

2、 給一個String 變數賦值為另外一個String 變數。

String s2 = s;


String對象不可變展示2變數s2 儲存這相同引用的值,它們都指向了同一對象的值。

 

3、串連String

 

s = s.concat("ef");


變數s 現在儲存的是新建立的sting對象的引用。

 

總結:
一旦一個string 被在記憶體(堆)中建立,它就是不可以被改變的。我們應該注意的是所有的String方法都不會改變一個string的本身,而是返回一個新的string。

如果我們需要一個可以被改變的string,那麼我們可以使用StringBuffer(譯者註:安全執行緒)或StringBuilder。否則每建立一個新的string的時候,會浪費大量的時間在垃圾收集上。

這裡有個StringBuilder的應用例子。

public static String readFileToString() throws IOException {        File dirs = new File(".");        String filePath = dirs.getCanonicalPath() + File.separator+"src"+File.separator+"TestRead.java";         StringBuilder fileData = new StringBuilder(1000);//Constructs a string buffer with no characters in it and the specified initial capacity        BufferedReader reader = new BufferedReader(new FileReader(filePath));         char[] buf = new char[1024];        int numRead = 0;        while ((numRead = reader.read(buf)) != -1) {            String readData = String.valueOf(buf, 0, numRead);            fileData.append(readData);            buf = new char[1024];        }         reader.close();         String returnStr = fileData.toString();        System.out.println(returnStr);        return returnStr;    }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.