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