Java中字符串的不可变性

来源:互联网 发布:空气人形 知乎 编辑:程序博客网 时间:2024/06/02 07:42

1.声明一个字符串

String s = "abcd";
s存储了字符串对象的引用。下面的箭头可以理解为“store reference of”。

2.将一个字符串变量赋给另一个字符串变量

String s2 = s;

s2存储了相同的引用值,它们指向相同的字符串对象。

3.连接字符串

s = s.concat("ef");

s现在存储一个新创建的字符串对象的引用。

总结

只要一个字符串在内存中(heap)创建,就不能被改变。我们需要注意有关字符串的所有方法都不会该变字符串本身,而会返回一个新字符串。
如果你需要可被改变的字符串,我们可以使用StringBuffer或者StringBuilder。否则,每创建一个新字符串,都会浪费大量时间在垃圾收集上。下面是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 capacityBufferedReader 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;}

0 0