4個字符 “我們”算幾個字符?
計算字符串的字節數:
getBytes()length//UTF-8編碼下一個字佔3個字節
getBytes("gb2312").length//gb2312編碼下一個字佔2個字節
public byte[] getBytes(Charset charset) {
String canonicalCharsetName = charset.name();
if (canonicalCharsetName.equals("UTF-8")) {
return Charsets.toUtf8Bytes(value, offset, count);
} else if (canonicalCharsetName.equals("ISO-8859-1")) {
return Charsets.toIsoLatin1Bytes(value, offset, count);
} else if (canonicalCharsetName.equals("US-ASCII")) {
return Charsets.toAsciiBytes(value, offset, count);
} else if (canonicalCharsetName.equals("UTF-16BE")) {
return Charsets.toBigEndianUtf16Bytes(value, offset, count);
} else {
CharBuffer chars = CharBuffer.wrap(this.value, this.offset, this.count);
ByteBuffer buffer = charset.encode(chars.asReadOnlyBuffer());
byte[] bytes = new byte[buffer.limit()];
buffer.get(bytes);
return bytes;
}
}
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
本文將用3個圖片來解釋Java中String的不可變性().
1. 聲明String對象
- String s = "abcd";
String s = "abcd";
- String s2 = s;
String s2 = s;
- s = s.concat("ef");
- // s = s + "ef"; // 等價
s = s.concat("ef");
// s = s + "ef"; // 等價
一個String對象在 堆內存 中創建以後, 就不能被改變了. 請注意String對象的所有方法都不會改變其本身,而是會返回一個新的String對象.
如果我們需要可改變的字符串,則需要使用 StringBuffer 或者 StringBuilder. 否則每次創建一個新String對象的話,就會造成大量的內存浪費,需要耗時來執行垃圾回收。可以參考: StringBuilder的使用示例
相關文章:
1. 十大常見Java String問題
2. Java Code – Convert a file to a String
3. String is passed by “reference” in Java
4. The interface and class hierarchy diagram for collections with an example program