星空网 > 软件开发 > Java

一、图解Java中String不可变性

这里有一堆例子来说明Java的String的不可变性。

1、声明一个String

String s = "abcd";


一、图解Java中String不可变性
s 变量保存string对象的引用,下面的箭头解释成保存了哪个对象的引用。

 

2、 给一个String 变量赋值为另外一个String 变量。

String s2 = s;


String对象不可变展示2变量s2 保存这相同引用的值,它们都指向了同一对象的值。

 

3、连接String

 

s = s.concat("ef");


变量s 现在保存的是新创建的sting对象的引用。

 

一、图解Java中String不可变性

总结:
一旦一个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;  }



原标题:一、图解Java中String不可变性

关键词:JAVA

*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: admin#shaoqun.com (#换成@)。

巴巴多斯旅游景点推荐:https://www.vstour.cn/t/巴巴多斯旅游景点推荐.html
巴巴多斯旅游酒店预定:https://www.vstour.cn/t/巴巴多斯旅游酒店预定.html
巴巴多斯旅游胜地:https://www.vstour.cn/t/巴巴多斯旅游胜地.html
巴巴多斯旅游团:https://www.vstour.cn/t/巴巴多斯旅游团.html
巴巴多斯旅游网:https://www.vstour.cn/t/巴巴多斯旅游网.html
巴巴多斯旅游网站大全:https://www.vstour.cn/t/巴巴多斯旅游网站大全.html
珠海长隆横琴剧院有多少座位:https://www.vstour.cn/a/334172.html
珠海长隆横琴剧院在哪里?附禁带物品:https://www.vstour.cn/a/334173.html
相关文章
我的浏览记录
最新相关资讯
跨境电商服务平台 | 深圳旅行社 | 东南亚物流