Java 字符串构造函数

标签 java string constructor

来自 String 类:

public String(byte[] bytes,
      int offset,
      int length)

Java 文档:

Constructs a new String by decoding the specified subarray of bytes using the platform's default charset.

The length of the new String is a function of the charset, and hence may not be equal to the length of the subarray.

The behavior of this constructor when the given bytes are not valid in the default charset is unspecified. The CharsetDecoder class should be used when more control over the decoding process is required.

粗体部分是什么意思?

最佳答案

The length of the new String is a function of the charset, and hence may not be equal to the length of the subarray.

在某些字符集中,某些甚至所有字符都使用多个字节。因此给定长度的数组可能会产生较短的字符串。不要假设 1 个字节 = 1 个字符。

The behavior of this constructor when the given bytes are not valid in the default charset is unspecified. The CharsetDecoder class should be used when more control over the decoding process is required.

如果您使用某些字符集解码字符串,并且字节数组包含该字符集未知的值,则会出现未定义的行为。例如,如果字符集使用 0 到 127 之间的值,并且您的数组包含值 -5,则会出现未定义的行为。

关于Java 字符串构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50375313/

相关文章:

java - 为什么我们需要在实体中声明 NOT 空构造函数?

c# - 在派生构造函数中的某个代码块之后调用派生类中的基类构造函数

java - BeanToPropertyValueTransformer 和 commons-collections4

Java - List<String> 打印\n 而不是显示换行符

c# - 为 C# 包装 native DLL

json - 有没有更快的方法来解析 Java 中有效整数的字符串?

javascript - 使新关键字可选

JAVA字典作为参数

java - 检测硬编码密码

java - 如何在后台运行